Reputation: 51
I'm Django beginner. I am trying to implement a code on how to implement a comment form in home page and also display its comments.
class Image(models.Model):
imageuploader_profile=models.ForeignKey(settings.AUTH_USER_MODEL)
upload_image=models.ImageField()
class Comments(models.Model):
user=models.ForeignKey(settings.AUTH_USER_MODEL)
commented_image=models.ForeignKey(Image,....)
comment_post=models.TextField()
def home(request):
if request.method == 'POST':
form=CommentForm(request. POST)
if form.is_valid():
comment=form.save(commit=False)
comment.user=request.user
comment.commented_image=post
comment.save()
return redirect....
else:
form=CommentForm
HOME template
{% for comment in all_images %}
{{ comment.comment_post }}
{% endfor %}
Upvotes: 0
Views: 96
Reputation: 1490
Changed context in your second image, see if this solves the problem.
context = {'all_images': all_images, 'comments': comments}
Edited:
Edit home.html
{% for image in all_images %}
<img src="{{ image.upload_image"}} />
{% for comment in comments %}
{% if comment.commented_image == image %}
{{ comment.comment_post }}
{% else %}
No comments available.
{% endif %}
{% endfor %}
{% endfor %}
Edited (2): For count of comments without active do:
Edit views.py
# change
all_images = Image.objects.filter(imageuploader_profile=request.user)
...
for image in all_images:
images_comment_count = []
images_comment_count.append(Comments.objects.filter(commented_image_id=image.id, active=True).count())
...
context = {..., 'images_comment_count': images_comment_count}
Now, edit home.html
{% load index %}
...
{% for image in all_images %}
<img src="{{ image.upload_image"}} />
{% for comment in comments %}
{% if comment.commented_image == image %}
{{ comment.comment_post }}
{% else %}
No comments available.
{% endif %}
{% endfor %}
<!-- Comment Count CHANGED THIS -->
{{ images_comment_count|index:forloop.counter0 }}
{% endfor %}
Edit 3:
yeah it shows it because we will now be creating custom tag filter.
1) create templatetags/ directory in the same apps folder
2) create a file called __init__.py
3) create another file called index.py
we will be filling this file
4) Add the given code in index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]
Upvotes: 1