Reputation: 1270
Comment is not adding after clicking it on Add comment,
models.py
class Comment(models.Model):
post_by = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments')
body = models.TextField()
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_at']
def __str__(self):
return self.body
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
Please help me in this. I will really appreciate your Help.
Upvotes: 0
Views: 68
Reputation: 476574
You should specify the action where the form has to submit to, so:
<form method="post" action="{% url 'name-of-detail-view' id=post.pk %}" style="margin-top: 1.3em;">
{{ comment_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
where 'name-of-the-detail-view'
should be the name of the view where you handle the comment.
Your view also has some anti-patterns. You can improve this with:
from django.shortcuts import get_object_or_404
@login_required
def detail_view(request, id):
data = get_object_or_404(Post, pk=id)
comments = data.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.post_by = data
comment_form.instance.commented_by = request.user
# shouldn't the comment be active by default?
comment_form.instance.active = True # ??
new_comment = comment_form.save()
return redirect(detail_view, pk=pk)
else:
comment_form = CommentForm()
context = {'data':data,'comments':comments,'comment_form':comment_form}
return render(request, 'mains/show_more.html', context )
Upvotes: 1
Reputation: 2165
couldn't see a problem with templates or else, try this little modification in the views.py ,hope it could help
from django.shortcuts import render, get_object_or_404
@login_required
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, id=id)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'mains/show_more.html', {'post': post,
'comments':comments, 'new_comment': new_comment,
'comment_form': comment_form})
Upvotes: 1