[Python] How to tag a comment with the blog post in django?

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    i am new to django and am currently working on developing a blog.

    I am trying to insert a comment form for my viewers using the CreateView template. Viewers will need to log in to type their comment. Their username will be tagged to the comment for the respective blog without them needing to indicate anything. There are no errors but data is not stored as expected. Comment is accepted but does not appear on the blog. Went to check on django administration where apparently only the author is stored but not the blog post that comment is on. Below is my code that is stored in the (views.py).

    class CommentCreate(LoginRequiredMixin,CreateView):
    model = Comment
    fields = ['comment','blog']
    template_name = 'catalog/blog_comment.html'

    def get_context_data(self, **kwargs):
    context = super(CommentCreate, self).get_context_data(**kwargs)
    context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk'])
    return context

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

    def get_success_url(self):
    return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'],})


    The models Blog and Comment is defined as below in a separate file (models.py)

    class Blog(models.Model):
    title = models.CharField(max_length=200)
    blogger = models.ForeignKey('Blogger', on_delete=models.SET_NULL,
    null=True)
    content = models.TextField(max_length=1000, help_text='Write some stuffs
    for your blog')
    post_date = models.DateField(default=date.today)

    class Meta:
    ordering = ['post_date',"title","blogger"]

    def __str__(self):
    return self.title

    def get_absolute_url(self):
    return reverse('blog-detail', args=[str(self.id)])


    class Comment(models.Model):
    comment = models.TextField(max_length=1000, help_text='Comment on the
    blog')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    blog = models.ForeignKey("Blog", on_delete=models.SET_NULL, null=True)
    post_date = models.DateTimeField(auto_now_add=True)

    class Meta:
    ordering = ['-post_date']

    def __str__(self):
    return self.comment


    Any advice is appreciated. Thank you.

    Continue reading...

Compartilhe esta Página