如何使用CreateView将用户对象传递给Modelform

时间:2019-02-08 15:31:56

标签: django django-class-based-views modelform

NOT NULL约束失败:blog_post.author_id

嗨,我是django的新手,无法修复此错误。

我正在构建一个博客应用,我希望作者成为当前用户。
我知道我没有正确地将用户对象传递给表单,但是我发现的任何解决方案都不适合我。

提前谢谢!

models.py

class User(auth.models.User,auth.models.PermissionsMixin):
    def __str__(self):
        return '@{}'.format(self.username)


class Post(models.Model):
    author = models.OneToOneField(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()

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

forms.py

class UserForm(UserCreationForm):
    class Meta:
        fields = ('username', 'email', 'password1', 'password2')
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


 class PostForm(forms.ModelForm):
     class Meta:
         model = Post
         fields = ('title', 'text',)

views.py

class SignUpView(CreateView):
    form_class = UserForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

class PostCreateView(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'

    form_class = PostForm
    model = Post

2 个答案:

答案 0 :(得分:0)

您的代码不错,只是您没有传递User对象来更新作者字段。

我认为在您的PostCreateView中,您可以执行以下操作:

class PostCreateView(LoginRequiredMixin, CreateView):
     login_url = '/login/'
     redirect_field_name = 'blog/post_detail.html'
     form_class = PostForm
     model = Post

     def valid_form(self,form, **kwargs):
         form.instance.author = self.request.user
         super(PosetCreateView, self).get_context_data(kwargs)

         return HttpResponse('/')

答案 1 :(得分:0)

我找到了一种适用于我的情况的解决方案,与您的@Silas非常相似。

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'
    form_class = PostForm
    model = Post

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.author = self.request.user
        self.object.save()
        return super().form_valid(form)

models.py

class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
...