Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : saving form to 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" />
...

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

like image 278
Deepankar Bajpeyi Avatar asked May 21 '26 03:05

Deepankar Bajpeyi


2 Answers

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.

like image 137
Nick Bewley Avatar answered May 23 '26 17:05

Nick Bewley


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()})
like image 27
catherine Avatar answered May 23 '26 16:05

catherine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!