如何在 django(Python) 中为文章添加评论?

我是 Django 新手,我在教程后重复一遍,但我无法显示来自 html 数据库的注释。


urls.py


static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

设置


    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

models.py


from django.db import models

class Post(models.Model):

    photo       = models.ImageField(upload_to='media/photos/',null=True, blank=True)

    name_barber = models.CharField(max_length=30)

    description = models.TextField(blank=True, null=True)


    def __str__(self):

        return self.description[:10]


class Comment(models.Model):

    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)

    name = models.CharField(max_length=255)

    body = models.TextField()

    date_add = models.DateTimeField(auto_now_add=True)



    def __str__(self):

        return '%s - %s' % (self.post, self.name)

html文件


} </style>

{% for post in posts %}

<img src="{{MEDIA_URL}}{{post.photo.url}}" width="800"  />


<h3>{{ post.name_barber}}</h3>

<p>{{ post.description}}</p>

{% endfor %}



<h3> Comments.. </h3>


{% if not post.comments.all %}

    no comments yet...<a href = "#">Add one</a>


{% else %}


    {% for comment in post.comments.all %}


    <strong>

        {{ comment.name }}

        {{ comment.date_add }}

    </strong>

        {{comment.body }}

     {% endfor %}

{% endif %}

通过管理面板添加评论后,页面显示:还没有评论.. 有什么问题请告诉我?


吃鸡游戏
浏览 1375回答 1
1回答

POPMUISE

删除条件并将标签与 forloop 一起if/else使用。{% empty %}&nbsp;{% for comment in post.comments.all %}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; <strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ comment.name }}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{ comment.date_add }}&nbsp; &nbsp; &nbsp; &nbsp; </strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{comment.body }}&nbsp; &nbsp; &nbsp; &nbsp; {% empty %}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;no comments yet...<a href = "#">Add one</a>&nbsp; {% endfor %}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python