55

我有一个模型:

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

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

更新:

解决方案移至下面的单独答案

4

4 回答 4

45

我通过覆盖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)
于 2012-05-12T17:03:27.850 回答
15

我只是偶然发现了这个问题,这个线程引导我朝着正确的方向前进(谢谢!)。基于这个 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)
于 2016-06-18T22:06:45.340 回答
2

berislav 在views.py 中的代码对我不起作用。表单按预期呈现,用户值在隐藏输入中,但表单没有保存(我不知道为什么)。我尝试了一种稍微不同的方法,它对我有用:

视图.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
        }
于 2012-05-11T11:50:58.797 回答
1

您应该为该模型设置一个CreateViewusing 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
于 2012-05-01T04:32:47.010 回答