如何为评论中的帖子分配评论

编程入门 行业动态 更新时间:2024-10-27 16:33:21
本文介绍了如何为评论中的帖子分配评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是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=CommentForm

HOME模板

{% 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]

更多推荐

如何为评论中的帖子分配评论

本文发布于:2023-10-23 08:21:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520300.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   分配   帖子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!