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
The
new_commentvariable is not being used after it's set toNone, so remove it. Additionally, the code does not show any logic for saving the comment to the database, try to use the following view:The exact view would not work, since it assumes the following things:
This assumes that the user is logged in and the
request.userobject 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.Here
redirect("blog_detail"...)is added as you should always return anHttpResponseRedirectafter dealing withPOSTdata, the tip is not specific to Django, it's a good web practice in general. So you may have differentnamwof view, so you can change it accordingly.