我是Django初学者.我正在尝试实现有关如何在主页中实现评论表单并显示其评论的代码.
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 commentmented_image=post comment.save() return redirect.... else: form=CommentFormHOME模板
{% for comment in all_images %} {{ commentment_post }} {% endfor %}推荐答案
更改第二张图片中的上下文,看看是否可以解决问题.
Changed context in your second image, see if this solves the problem.
context = {'all_images': all_images, 'comments': comments}编辑 home.html
{% for image in all_images %} <img src="{{ image.upload_image"}} /> {% for comment in comments %} {% if commentmented_image == image %} {{ commentment_post }} {% else %} No comments available. {% endif %} {% endfor %} {% endfor %}编辑(2):对于没有活动的评论数,请执行以下操作:
Edited (2): For count of comments without active do:
编辑 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 commentmented_image == image %} {{ commentment_post }} {% else %} No comments available. {% endif %} {% endfor %} <!-- Comment Count CHANGED THIS --> {{ images_comment_count|index:forloop.counter0 }} {% endfor %}是的,它显示出来是因为我们现在将创建自定义标签过滤器.1)在同一apps文件夹中创建templatetags/目录2)创建一个名为 __ init __.py 的文件3)创建另一个名为 index.py 的文件,我们将填充该文件4)在 index.py
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]更多推荐
如何为评论中的帖子分配评论
发布评论