cosmos multi
cosmos multi

Reputation: 565

make a record by slug

I have a model which has a slug, but when trying to register it does not allow it, generating the following error not null constraint failed: commentaries_commentarie.post_id.

this is model:

class Commentarie(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    commentarie = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

this is urls:

urlpatterns = [
    path('<slug:slug>/', views.CommentarieCreateView.as_view(), name='add_commentarie'),
]

this is view:

class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()
        return redirect('posts:post')

also try to create the relation, getting directly by the kwarg but it generates an error, because it turns out that it is waiting for a pk object, and it slug it is generated correctly

Upvotes: 0

Views: 33

Answers (1)

Daniel Morell
Daniel Morell

Reputation: 2586

Your post property in Commentarie cannot be null in the database. You need to either provide a value or allow it to be null.

To set the post object you can do something like this...

class CommentarieCreateView(CreateView):
    template_name = 'commentaries/commentarie.html'
    model = Commentarie
    form_class = CommentarieForm

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.post = # A Post object
        self.object.save()
        return redirect('posts:post')

To allow it to be null change it to...

class Commentarie(models.Model):
    ...
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
    ...

Once you change it you will need to run your database migration again.

Upvotes: 1

Related Questions