ModelForm,用户是request.user

时间:2017-08-19 19:13:37

标签: django django-models django-forms

我试图制作一个用户可以提交帖子/文章的表单。

我有这个型号:

class Post(models.Model):
    title = models.CharField(max_length=150)
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

此表格:

class PostForm(forms.ModelForm):
    title = forms.CharField(required=True)
    content = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = Post
        fields = ['title', 'content']

这个观点:

class PostCreateView(FormView):
    form_class = PostForm
    template_name = 'template/create_post.html'
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        response = super(PostCreateView, self).form_valid(form)
        form.user = self.request.user
        form.save()
        return response

我已设置好用户,但我还是

IntegrityError at /new-post/ NOT NULL constraint failed: cyth_post.user_id

这里是完整的追溯电话:http://dpaste.com/0PJSTY2

我在这里做错了什么?

提前感谢您的回答!

1 个答案:

答案 0 :(得分:2)

您需要设置form.instance用户,然后运行超级

def form_valid(self, form):
    form.instance.user = self.request.user
    return super(PostCreateView, self).form_valid(form)