如果我没有使用ModelForm
指定其模型,Django如何知道一个表单与哪个数据库表相关?你看,用这样的形式:
from django import forms
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget=forms.Textarea)
Django如何知道必须在模型X中保存这些数据?
对我来说,当你使用它时很明显:
from django.forms import ModelForm
from myapp.models import Article
class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']
答案 0 :(得分:6)
您需要在视图中将表单与模型相关联。如:
form = CommentForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
url = form.cleaned_data['url']
comment = form.cleaned_data['comment']
my_comment = Comment(name=name,url=url,comment=comment)
my_comment.save()