Search code examples
pythondjangowebcomments

comment on a blog post django


I m trying to make a comment system on a blog website with using the slug instead of pk im running into not NULL constraint failed: home_comment.post_id error

my error is coming in the form_valid function in the class based view

form.instance.post_id = self.kwargs['pk']

how do i do this ^ with the slug

form.instance.post__slug = self.kwargs['slug'] (this is showing an error)

views.py

class AddCommentView(CreateView):
    model = Comment
    form_class = AddCommentForm
    template_name = "add_comment.html"

    def form_valid(self, form):
        form.instance.post__slug = self.kwargs["slug"]
        form.instance.name = self.request.user
        return super().form_valid(form)

models.py

class Post(models.Model):
    title = models.CharField(max_length=1000, default="Title")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.CharField(max_length=1000, default="Category")
    body = models.TextField(default="This is the Body of the Post.")
    slug = models.SlugField(max_length=1000, null=True, blank=True)
    created_time = models.DateTimeField(auto_now_add=True)
    created_date = models.DateField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)
    updated_date = models.DateField(auto_now=True)
    likes = models.ManyToManyField(User, related_name="blog_posts_likes")
    dislikes = models.ManyToManyField(User, related_name="blog_posts_dislikes")

    class Meta:
        verbose_name_plural = "Blogs & Posts"

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = generate_slug(self.title)
        super(Post, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return f"/blogs/post/{self.slug}"

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
    name = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    date_added = models.DateField(auto_now_add=True)
    time_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Post Comments"

    def __str__(self):
        return "%s - %s" % (self.post.title, self.name.username)

    def get_absolute_url(self):
        return f"/blogs/post/{self.post.slug}"

html file

{% extends "base.html" %}

{% block content %}

{% if user.is_authenticated %}

<section class="text-gray-600 body-font relative">
    <div class="container px-5 py-24 mx-auto">
        <div class="flex flex-col text-center w-full mb-12">
            <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Add A Comment</h1>
        </div>
        <div class="mx-auto">
            <form method="post">
                {% csrf_token %}
                {{form}}
                <div class="p-2 w-full">
                    <button
                        class="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg">Add</button>

                </div>
                <div class="p-2 w-full pt-8 mt-8 border-t border-gray-200 text-center">
                </div>
            </form>
        </div>
    </div>
</section>


{% endif %}

{% endblock %}

Solution

  • try this

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