小编典典

如何在CreateView中设置ForeignKey?

django

我有一个模型:

class Article(models.Model):
    text = models.CharField()
    author = models.ForeignKey(User)

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


阅读 453

收藏
2020-03-29

共1个答案

小编典典

我通过覆盖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)
2020-03-29