簡體   English   中英

Django HTML模板不呈現內容

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM