[英]Django forms, specifying Model
I have the following form: 我有以下表格:
class NotesForm(forms.Form):
text = forms.CharField(widget = forms.Textarea)
With the following views.py: 使用以下views.py:
if request.POST:
form = ThisForm(request.POST)
if form.is_valid():
newentry = form.save()
HttpResponseRedirect('/')
And the folowing models.py 还有下面的models.py
class TheModel(models.Model):
text = models.TextField()
The thing is that it gives me 'ThisForm' object has no attribute 'save'
which it is most likely because I have not linked any model to it. 关键是它给了我'ThisForm' object has no attribute 'save'
,这很可能是因为我没有将任何模型链接到它。
How can I link a model to the form in order to be able to form.save()
to the database? 如何将模型链接到表单,以便能够将form.save()
到数据库?
I'm thinking you are wanting a forms.ModelForm
instead of forms.Form
: 我在想你想要一个forms.ModelForm
而不是forms.Form
:
class ThisForm(forms.ModelForm):
class Meta:
model = TheModel
fields = ['text']
Then your view should be able to form.save()
. 然后,您的视图应该可以form.save()
。 See here for the official documentation. 请参阅此处获取官方文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.