pythondjangodjango-modelsdjango-viewsdjango-comments

How to write a comment and reply with django with this model?


I'm a newcomer and I have this problem that I can't send this comment to database it just refreshes the page and nothing happens.

def blog_detail(request , id):

    post = Post.objects.get(pk = id , status = True)
    comments = post.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_content = request.POST['comment_content']

        if comment_content == '' or comment_content == None :
            messages.error(request , 'comment is empty')


        try:
            comment = Comment.objects.get(body=comment_content,name=MyUser.first_name,email=MyUser.email,active=False)
        except:
            Comment.DoesNotExist()
            new_comment = None      
    
    return render(request, 'blog/blog-detail.html', {'post': post,
                                           'comments': comments,
                                                                                   })

this is my model:

class Comment(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)

I can't idenity the problem


Solution

  • The new_comment variable is not being used after it's set to None, so remove it. Additionally, the code does not show any logic for saving the comment to the database, try to use the following view:

    def blog_detail(request , id):
        post = Post.objects.get(pk=id, status=True)
        comments = post.comments.filter(active=True)
    
        # Comment posted
        if request.method == 'POST':
            comment_content = request.POST.get('comment_content')
    
            if not comment_content:
                messages.error(request, 'Comment is empty')
            else:
                try:
                    comment = Comment.objects.get(
                        body=comment_content,
                        name=request.user.first_name,
                        email=request.user.email,
                        active=False,
                        post=post
                    )
                    messages.error(request, 'You have already submitted this comment.')
                except Comment.DoesNotExist:
                    comment = Comment.objects.create(
                        post=post,
                        name=request.user.first_name,
                        email=request.user.email,
                        body=comment_content,
                        active=True
                    )
                    messages.success(request, 'Comment submitted successfully.')
                    return redirect('blog_detail', id=id)
    
        return render(request, 'blog/blog-detail.html', {'post': post, 'comments': comments})
    

    The exact view would not work, since it assumes the following things:

    1. This assumes that the user is logged in and the request.user object contains the necessary details. If the user is not logged in, you may need to modify the code to prompt them to log in or provide their name and email address before submitting the comment.

    2. Here redirect("blog_detail"...) is added as you should always return an HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general. So you may have different namw of view, so you can change it accordingly.