![](/img/trans.png)
[英]html template not rendering correctly for dynamic html content in django
[英]Django HTML template not rendering content
我正在构建一个通知系统。 我几乎完成了通知系统。 现在我的问题是通知内容没有呈现我的 html 模板。 我不明白我在哪里做错了。这是我的代码:
通知模型.py:
class Notifications(models.Model):
blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE)
NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'))
sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user")
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user")
notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250)
text_preview = models.CharField(max_length=500, blank=True)
date = models.DateTimeField(auto_now_add=True)
is_seen = models.BooleanField(default=False)
视图.py
def ShowNOtifications(request):
user = request.user
notifications = Notifications.objects.filter(user=user).order_by('-date')
Notifications.objects.filter(user=user, is_seen=False).update(is_seen=True)
template_name ='blog/notifications.html'
context = {
'notify': notifications,
}
return render(request,template_name,context)
#html
{% for notification in notifications %}
{% if notification.notification_type == "New Comment" %}
@{{ notification.sender.username }}You have received new commnet
<p>{{ notification.text_preview }}</p>
{%endif%}
{%endfor%}
为什么通知内容没有显示在我的 html 模板中? 我在哪里做错了?
您做错的第一件事是使用字典中的值在模板中呈现。 而是使用密钥,因此您的代码应该是:
{% for notification in notify %}
{% if notification.NOTIFICATION_TYPES == "New Comment" %}
@{{ notification.sender}}You have received new commnet
<p>{{ notification.text_preview }}</p>
{%endif%}
{%endfor%}
在您的模板中,您希望通过notifications
循环,但 Django 模板找不到notifications
因为您在上下文中使用标签'notify'
context = {
'notify': notifications,
}
因此,在您的views.py
,您可以将'notify'
更改为'notifications'
:
context = {
'notifications': notifications,
}
您可以在此处查看文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.