3

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" />
...

Here is how I am saving the form using 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 html form add.html have the EXACT mappings as my model Recipe ?
If yes ,then

  1. How do I add the corresponding types in the html form (for posted_on) ?
  2. How do I handle the id that is implicitly created by syncdb?
  3. Is there any alternative ?

I have just started to learn Django

2 Answers 2

4

1) Change posted_on to automatically add the date posted.

posted_on = models.DateTimeField(auto_now_add=True)

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

3) Why not use a ModelForm for this? Documentation.

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

You can either use exclude or include on fields to make sure your form only contains the fields from Recipe that you want to include in your form.

Sign up to request clarification or add additional context in comments.

Comments

2

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()})

4 Comments

This is not what i want . I want the views to add the data to the db. In your page.html There is way a user can input the fields . :(
yeah, that's what I did. My views can save the data into your db. I use your RecipeForm() and my page.html has a form that can input data then submit
You always get form invalid because there are no data submitted. The form you construct is another form, it's not your ModelForm. Just try and you will learn.
@Deepanker: your data is saved to the database when form.save() is called. Cathy is right about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.