我有一个模型:
class Article(models.Model): text = models.CharField() author = models.ForeignKey(User)
如何编写基于类的视图,该视图创建新的模型实例并将author外键设置为request.user?
author
request.user
我通过覆盖form_valid方法解决了这个问题。下面是详细说明的样式:
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)