简体   繁体   English

Django HTML模板不呈现内容

[英]Django HTML template not rendering content

I am building an notifcation system.我正在构建一个通知系统。 I am almost complete the notifcation system.我几乎完成了通知系统。 Now my problem is notifcation content not rendering my html template.现在我的问题是通知内容没有呈现我的 html 模板。 I am not understanding where I am doing mistake.here is my code:我不明白我在哪里做错了。这是我的代码:

notifications models.py:通知模型.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)

views.py视图.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 #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%}

why notification content not showing in my html template?为什么通知内容没有显示在我的 html 模板中? where I am doing mistake?我在哪里做错了?

First thing you are doing wrong is using the value in dictionary to render in the template.您做错的第一件事是使用字典中的值在模板中呈现。 Rather use the key, so your code should be:而是使用密钥,因此您的代码应该是:

{% for notification in notify %} 
{% if notification.NOTIFICATION_TYPES == "New Comment" %}

@{{ notification.sender}}You have received new commnet 
      <p>{{ notification.text_preview }}</p>
{%endif%}
{%endfor%}

In your template you want loop through notifications but Django template can't find notifications because you declare in your context with label 'notify'在您的模板中,您希望通过notifications循环,但 Django 模板找不到notifications因为您在上下文中使用标签'notify'

context = {
    'notify': notifications,
}

So in your views.py , you can change 'notify' to 'notifications' :因此,在您的views.py ,您可以将'notify'更改为'notifications'

context = {
    'notifications': notifications,
}

You can see document here您可以在此处查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM