提交ModelForm
后,如何添加外键关系才能验证?
models.py
class Comment(models.Model):
id = models.AutoField(primary_key=True)
activity = models.ForeignKey(Activity)
submitter = models.ForeignKey(User)
creation_date = models.DateTimeField(auto_now_add=True)
content = models.TextField()
forms.py
class CommentForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
views.py
def index(request, id=None):
activity_instance = Activity.objects.get(pk=1)
submitter_instance = User.objects.get(id=1)
newComment = CommentForm(request.POST)
newComment.activity = activity_instance
newComment.submitter = submitter_instance
if newComment.is_valid(): # <-- false, which is the problem
答案 0 :(得分:5)
我认为你正在将表单实例与模型实例混合在一起。您的newComment
是一个表单,将其他对象指定为表单属性不会使表单保存外键(不确定您在哪里找到此用法),因为所有表单数据都保存在form.data
中,这是一个类似数据结构的词典。
我不确定您的表单是什么样的,因为您没有排除外键,因此它们应该作为下拉列表呈现,您可以选择它们。如果您不希望用户选择外键但选择按照您当前的方式分配值,则应将其排除在form.is_valid()
将通过的表单中:
class CommentForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Comment
exclude = ('activity', 'submitter')
views.py
def index(request, id=None):
activity_instance = Activity.objects.get(pk=1)
submitter_instance = User.objects.get(id=1)
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.activity = activity_instance
new_comment.submitter = submitter_instance
new_comment.save()
Django doc about save()
method。