如何为评论中的帖子分配评论 [英] How to assign comment to the post commented on

查看:70
本文介绍了如何为评论中的帖子分配评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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
            comment.commented_image=post
            comment.save()
            return redirect.... 
    else:
        form=CommentForm

HOME模板

{% for comment  in all_images %}
{{ comment.comment_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 comment.commented_image == image %}  
     {{ comment.comment_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 comment.commented_image == image %}  
     {{ comment.comment_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]

这篇关于如何为评论中的帖子分配评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆