Skip to main content
 首页 » 编程设计

python之django 在表单提交后添加外键值

2025年05月04日43daizhj

提交ModelForm后,如何添加外键关系使其生效?

模型.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() 

表单.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 

请您参考如下方法:

我认为您混淆了表单实例和模型实例。你的 newComment 是一个表单,将其他对象分配为表单属性不会使表单保存外键(不确定你在哪里找到这个用法),因为所有表单数据都保存在 form.data,这是一个类似字典的数据结构。

我不确定您的表单是什么样的,因为您没有排除外键,因此它们应该呈现为下拉列表并且您可以选择它们。如果您不希望用户选择外键,而是选择像您目前所做的那样分配值,您应该在表单中排除它们,这样 form.is_valid() 就会通过:

class CommentForm(forms.ModelForm): 
    content = forms.CharField(widget=forms.Textarea) 
 
    class Meta: 
        model = Comment 
        exclude = ('activity', 'submitter') 

View .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 文档 about save() method .