我有一个模型:
class Article(models.Model):
text = models.CharField()
author = models.ForeignKey(User)
如何编写创建新模型实例并将author
外键设置为的基于类的视图request.user
?
更新:
解决方案移至下面的单独答案。
我有一个模型:
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)
我只是偶然发现了这个问题,这个线程引导我朝着正确的方向前进(谢谢!)。基于这个 Django 文档页面,我们可以完全避免调用表单的save()
方法:
class CreateArticle(LoginRequiredMixin, CreateView):
model = Article
def form_valid(self, form):
form.instance.author = self.request.user
return super(CreateArticle, self).form_valid(form)
berislav 在views.py 中的代码对我不起作用。表单按预期呈现,用户值在隐藏输入中,但表单没有保存(我不知道为什么)。我尝试了一种稍微不同的方法,它对我有用:
from django.views.generic import *
from myapp.forms import ArticleForm
from myapp.models import Article
class NewArticleView(CreateView):
model = Article
form_class = ArticleForm
def get_initial(self):
return {
"user": self.request.user
}
您应该为该模型设置一个CreateView
using a 。ModelForm
在表单定义中,您将 设置ForeignKey
为具有HiddenInput
小部件,然后使用get_form
视图上的方法来设置用户的值:
表格.py:
from django import forms
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
widgets = {"user": forms.HiddenInput()}
视图.py:
from django.views.generic import *
from myapp.forms import ArticleForm
from myapp.models import Article
class NewArticleView(CreateView):
model = Article
form_class = ArticleForm
def get_form(self, form_class):
initials = {
"user": self.request.user
}
form = form_class(initial=initials)
return form