Search code examples
djangodjango-viewscommentsslug

How to show comment on blogpost with slug instead of pk


I want to show the comment underneath an article, but I use a slug instead of a pk. I got the following error:

IntegrityError at /blogpost-2/comment/ NOT NULL constraint failed: blog_comment.post_id

This is my code:

#models.py

`class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)`

#views.py

`class AddCommentView(CreateView):
    model = Comment 
    form_class = CommentForm
    template_name = "add_comment.html"
    #fields = '__all__'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)
    
    success_url = reverse_lazy('blog')`

#urls.py

`from django.urls import path
from . import views
from .views import BlogView, ArticleView, CategoryView, AddCommentView
urlpatterns = [
    path('<slug:slug>', ArticleView.as_view(), name='blogpost'),
    path('blog/', BlogView.as_view(), name='blog'),
    path('categorie/<str:cats>/', CategoryView, name='category'),
    path('<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'),
]`

#template add_comment.html

`{% extends 'base.html' %}
{% load static %}
{% block content %}
  <h1>Voeg een reactie toe..</h1>
  <div class="form-group">
    <form method="POST">
      {% csrf_token %}
      {{ form.as_p }}
      <button class="btn btn-primary">Voeg toe</button>
    </form>
  </div>
{% endblock %}`

I tried this code, but doesn't work...

    def form_valid(self, form):
        form.instance.post_slug = self.kwargs['slug']
        return super().form_valid(form)

Solution

  • You will need to query the post first:

    def form_valid(self, form):
        form.instance.post = Post.objects.get(slug=self.kwargs['slug'])
        return super().form_valid(form)