Reputation: 59
I have written some code that allows users of a website to comment on photos in a picture gallery, using a form. However, when I test the code, no comments are displayed.
It would appear that Django is not processing the following code (from my HTML file for the photo gallery), given that 'Comment by' is not displayed on screen:
{% for comment in comments %}
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
<h4>Comment by</h4> {{ comment.user }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
This is my views.py code:
@login_required
def add_comment(request, image_id):
new_comment = None
template_name = 'add_comment.html'
image = get_object_or_404(Picture, id=image_id)
comment = image.comment.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object and don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'comment_form': comment_form, 'image': image,'comment': comment, 'new_comment': new_comment,'comment_form': comment_form}
return render(request, template_name, context)
Does anyone have any suggestions as to how I can fix this, please?
EDIT: The code, which I have revised slightly since making this post, is at: https://github.com/EmilyQuimby/my_now_and_then. Any feedback appreciated.
Thank you.
Jeff
Upvotes: 1
Views: 215
Reputation: 1323
In your context
you are not passing comments
only comment
to your HTML file. So the for loop in your template file {% for comment in comments %}
can't find the variable comments
to loop over. This means it does not enter the for loop to render your HTML.
Upvotes: 1