NOT NULL constraint failed: spring_post.publisher_id

146 Views Asked by At

I created a class base create view.When i try to submite the post model create view. it will return NOT NULL constraint failed: spring_post.publisher_id how can i set the publisher the get the current logged in user and set it to the post piblisher field. im a beginner this is the publisher field in my post model

    publisher=models.ForeignKey(User,on_delete=models.PROTECT)
#and this is my views
class PostCreateView(LoginRequiredMixin,CreateView):
    model=Post
    fields=['title','description']
    redirect_field_name="login"
1

There are 1 best solutions below

0
willeM_ Van Onsem On

You need to set the .publisher of the post, so:

class PostCreateView(LoginRequiredMixin,CreateView):
    model=Post
    fields = ['title','description']
    redirect_field_name = 'login'

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

You probably should also specify the success_url [Django-doc] to specify where to redirect to if the POST request was successful.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.