Django: saving a form to a database

So I have the following model:

class Recipe(models.Model):
        title = models.CharField(max_length=100)
        ingredients = models.TextField(max_length=200,help_text="Put the ingredients required for the recepies here !")
        instructions = models.TextField(max_length=500)

        posted_on = models.DateTimeField('Posted On')

        def __unicode__(self):
                return self.title

      

Now what I want to do is that I have a front-end in html called add.html which has a form like:

<!DOCTYPE html>


<head><title>New Recipe</title></head>
<body>
<h1>Add A new Recipe Here</h1>

<form action="/recipes/add/" method="post">
{% csrf_token  %}

<label>ID<label>
<input type="number" name="id"></input><br />

<label>Title </label>
<input type ="text" name="title"><br />

<label>Ingredients</label>
<input type="text" name="ingredients" />
<br />

<label>Instructions </label>
<input type="text" name="instructions" />
...

      

This is how I save the form with ModelForm

:

def add(request):
        if request.method == 'POST':
                form = RecipeForm(request.POST)
                if form.is_valid():

                        form.save()
                        #redirect
                        return HttpResponse("Thank you")
                else:
                        return HttpResponse("Form Not Valid")
        else:
                form = RecipeForm()

                context = Context({'form':form,})
                context.update(csrf(request))
                template = loader.get_template('myApp/add.html')
                return HttpResponse(template.render(context))

      

When I run this I always get "form Invalid"

So now my problem is, should the add.html html form display EXACT as my model recipe?
If yes, then

  • How do I add the appropriate types

    to the html form (for posted_on

    )?
  • How to handle id

    which is implicitly created syncdb

    ?
  • Is there any alternative?

I just started learning Django

+3


source to share


2 answers


1) Modify posted_on

to automatically add the published date.

posted_on = models.DateTimeField(auto_now_add=True)

      

2) Django will handle the pk id generation for you.



3) Why not use a ModelForm

for this? Documentation .

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe

      

You can use exclude

or include

on fields

to make sure that your form only contains the fields Recipe

that you want to include in your form.

+4


source


models.py

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    ingredients = models.TextField(max_length=200,help_text="Put the ingredients required for the recepies here !")
    instructions = models.TextField(max_length=500)

    posted_on = models.DateTimeField(auto_add_now=True)

    def __unicode__(self):
            return self.title

      

page.html



<!DOCTYPE html>

<head><title>New Recipe</title></head>
<body>
<h1>Add A new Recipe Here</h1>

<form action="/recipes/add/" method="post">
{% csrf_token  %}
     {% form.as_p %}
     <input type="submit" value="submit">
</form>
</body>
</html>

      

views.py

from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render

def add(request):
    if request.method == 'POST':
            form = RecipeForm(request.POST)
            if form.is_valid():
                form.save()
                    return HttpResponseRedirect(reverse('app_name:url'))
            else:
                messages.error(request, "Error")
    return render(request, 'myApp/add.html', {'form': RecipeForm()})

      

+2


source







All Articles