我是Django初学者。我正在尝试实现有关如何在主页中实现评论表单并显示其评论的代码。
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模板
{% for comment in all_images %}
{{ comment.comment_post }}
{% endfor %}
答案 0 :(得分:1)
更改第二张图片中的上下文,看看是否可以解决问题。
context = {'all_images': all_images, 'comments': comments}
编辑:
编辑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 %}
编辑(2): 对于没有活动的评论数,请执行以下操作:
编辑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}
现在,编辑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 %}
编辑3:
是的,它显示出来是因为我们现在将创建自定义标签过滤器。
1)在同一apps文件夹中创建templatetags /目录
2)创建一个名为__init__.py
的文件
3)创建另一个名为index.py
的文件,我们将填充该文件
4)在index.py
from django import template
register = template.Library()
@register.filter
def index(indexable, i):
return indexable[i]