将表单数据存储在数据库中

时间:2012-11-24 19:50:28

标签: django django-views

我无法弄清楚如何在数据库中存储一个简单的表单。我觉得我很接近,但我的views.py可能有些不对劲。这是我的代码,任何想法我做错了什么? (也在dpaste

# models.py
class IngredienceCategory(models.Model):
    name = models.CharField(max_length=30, unique=True)
    user = models.ForeignKey(User, null=True, blank=True)

    class Meta:
    verbose_name_plural = "Ingredience Categories"

    def __unicode__(self):
        return self.name

# forms.py
class CategoryForm(forms.Form):
    name = forms.CharField(max_length=30)

# views.py
@login_required
def newCategory(request):
    if request.method == 'POST':
        username = request.user.username
        cform = CategoryForm(request.POST)
        if cform.is_valid():
            formInstance = cform.save(commit = False)
            formInstance.user = username
            formInstance.name = cform.cleaned_data['name']
            formInstance =  IngredienceCategory.objects.filter(name=formInstance.name, user=formInstance.user)
            formInstance.save()
            # return HttpResponseRedirect('new-category/')
    else:
        form = CategoryForm()

    context = {'form': form}

    return render_to_response('new-category.html', context, context_instance=RequestContext(request))

# new-category.html
<h3>Insert New Category</h3>
<form action="/" method="post" id="food-form">{% csrf_token %} 
{{ form.as_p }}
<input type="submit" name="foodForm" value="Save" />
</form>

2 个答案:

答案 0 :(得分:2)

以下行在当前位置无效。在保存表单数据之前,该命令将执行数据库查询并将结果指定为查询集。

formInstance =  IngredienceCategory.objects.filter(name=formInstance.name, user=formInstance.user)

这应该有效:

将cform作为普通表单:

if cform.is_valid():
    formInstance = IngredienceCategory(user=request.user, cform.cleaned_data['name'])
    formInstance.save()

如果cform是ModelForm,你可以这样做:

if cform.is_valid():
    formInstance = cform.save(commit=False)
    formInstance.user = request.user
    formInstance.save()

我建议您查看ModelForms,因为它会根据您的模型构建清洁功能。

答案 1 :(得分:0)

您应该继承ModelForm

来自django.forms导入ModelForm class CategoryForm(ModelForm):      类Meta:          model = IngredienceCategory

有关如何呈现表单并将其保存到数据库,请参阅https://docs.djangoproject.com/en/dev/topics/forms/modelforms/