Django表单,指定Model

时间:2013-07-13 15:57:48

标签: python django forms

我有以下表格:

class NotesForm(forms.Form):
    text = forms.CharField(widget = forms.Textarea) 

使用以下views.py:

if request.POST:
        form = ThisForm(request.POST)
        if form.is_valid():
            newentry = form.save()
            HttpResponseRedirect('/')

以下是models.py

class TheModel(models.Model):
    text = models.TextField()

问题在于它给了我'ThisForm' object has no attribute 'save'这很可能是因为我没有将任何模型与它联系起来。

如何将模型链接到表单以便能够form.save()到数据库?

1 个答案:

答案 0 :(得分:1)

我想你想要forms.ModelForm而不是forms.Form

class ThisForm(forms.ModelForm):
    class Meta:
        model = TheModel
        fields = ['text']

然后您的观点应该能够form.save()See here for the official documentation.