如何在CreateView中设置ForeignKey?

我有一个模型:

class Article(models.Model):

text = models.CharField()

author = models.ForeignKey(User)

如何编写基于类的视图,该视图创建新的模型实例并将author外键设置为request.user

回答:

我通过覆盖form_valid方法解决了这个问题。下面是详细说明的样式:

class CreateArticle(CreateView):

model = Article

def form_valid(self, form):

article = form.save(commit=False)

article.author = self.request.user

#article.save() # This is redundant, see comments.

return super(CreateArticle, self).form_valid(form)

但是我们可以简短地说(感谢dowjones123),在docs中提到了这种情况。

class CreateArticle(CreateView):

model = Article

def form_valid(self, form):

form.instance.author = self.request.user

return super(CreateArticle, self).form_valid(form)

以上是 如何在CreateView中设置ForeignKey? 的全部内容, 来源链接: utcz.com/qa/405025.html

回到顶部