我有一个模特:
class Article(models.Model):
text = models.CharField()
author = models.ForeignKey(User)
如何编写基于类的视图来创建新模型实例并将author
外键设置为request.user
?
更新
解决方案已移至下方answer。
答案 0 :(得分:35)
我通过覆盖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),这个案例是mentioned in docs。:
class CreateArticle(CreateView):
model = Article
def form_valid(self, form):
form.instance.author = self.request.user
return super(CreateArticle, self).form_valid(form)
答案 1 :(得分:10)
我只是偶然发现了这个问题,这个线程让我朝着正确的方向前进(谢谢!)。根据{{3}},我们可以完全避免使用表单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)
答案 2 :(得分:2)
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
}
答案 3 :(得分:1)
您应该为该模型使用CreateView
设置ModelForm
。在表单定义中,您将ForeignKey
设置为HiddenInput
窗口小部件,然后在视图上使用get_form
方法设置用户的值:
forms.py:
from django import forms
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
widgets = {"user": forms.HiddenInput()}
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_form(self, form_class):
initials = {
"user": self.request.user
}
form = form_class(initial=initials)
return form