Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 填充外键的推荐方法?_Python_Sql_Django - Fatal编程技术网

Python 填充外键的推荐方法?

Python 填充外键的推荐方法?,python,sql,django,Python,Sql,Django,我有一个表story和comment,其中comment有一个story的外键,我使用一个modelform with comment作为模型,其中字段comment_文本将获得用户键入的数据,但是我还需要在comment表storyID中填充外键,该外键与它关联的story的值。我将故事ID作为view函数的参数,但我看不到在表单提交后将此值添加到表单中的任何方法,建议使用什么方法 编辑:使用视图和表单更新 这是一种观点: def add_comment(request, specific_s

我有一个表story和comment,其中comment有一个story的外键,我使用一个modelform with comment作为模型,其中字段comment_文本将获得用户键入的数据,但是我还需要在comment表storyID中填充外键,该外键与它关联的story的值。我将故事ID作为view函数的参数,但我看不到在表单提交后将此值添加到表单中的任何方法,建议使用什么方法

编辑:使用视图和表单更新

这是一种观点:

def add_comment(request, specific_story):
     """ Process a new comment """
     story_details = Story.objects.get(id=specific_story)

     if request.method == 'POST':
         form = NewComment(request.POST)
         if form.is_valid():
             form.save()
             return render(request, "base/story/display_story.html", {'story_details': story_details, 'form': form})
         else:
             form = NewComment()
             return render(request, "base/story/display_story.html", {'story_details': story_details, 'form': form})
     else:
         return render(request, "base/story/display_story.html", {'story_details': story_details })
表格:


请发布您的视图,form codeoriginal post使用view和form Code更新谢谢,考虑了commit=False,但没有想到save方法返回了对象:
class NewComment(ModelForm):
     class Meta:
         model = Comment
         fields = ['comment_text']
         widgets = {
             'comment_text': Textarea(attrs={'class': 'form-control'})
         }
if form.is_valid():
    comment = form.save(commit=False)
    comment.story = story_details
    comment.save()
    return ...