Django:将表单保存到数据库

时间:2013-02-01 18:48:53

标签: python django model-view-controller

所以我有以下模型:

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

现在我想要做的是我在html中有一个名为add.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  %}

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

以下是我使用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))

当我跑步时,我总是得到"form Invalid" 所以现在我的问题是,html表单add.html是否应该将EXACT映射作为我的模型配方? 如果是,那么

  1. 如何在html表单中添加相应的typesposted_on)?
  2. 如何处理id隐式创建的syncdb
  3. 还有其他选择吗?
  4. 我刚开始学习Django

2 个答案:

答案 0 :(得分:4)

1)更改posted_on以自动添加发布日期。

posted_on = models.DateTimeField(auto_now_add=True)

2)Django将为您处理pk id创建。

3)为什么不使用ModelForm呢? Documentation

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

您可以使用exclude上的includefields来确保您的表单只包含您希望包含在表单中的Recipe字段。

答案 1 :(得分: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()})