【问题标题】:Django HTML template not rendering contentDjango HTML模板不呈现内容
【发布时间】:2021-07-07 06:04:20
【问题描述】:

我正在构建一个通知系统。我几乎完成了通知系统。现在我的问题是通知内容没有呈现我的 html 模板。我不明白我在哪里做错了。这是我的代码:

通知 models.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

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 模板中?我在哪里做错了?

【问题讨论】:

  • 这不是问题的原因
  • 这行不通。我试过了
  • ahmad_fauzan458 你的解决方案是错误的。这是不同的场景
  • 在你的上下文中你声明'notify',所以在你的模板中你需要使用notify.sender.username而不是notification.sender.username
  • 我试过但没用

标签: django


【解决方案1】:

在您的模板中,您希望循环遍历 notifications,但 Django 模板找不到 notifications,因为您在上下文中使用标签 'notify' 声明

context = {
    'notify': notifications,
}

所以在您的views.py 中,您可以将'notify' 更改为'notifications'

context = {
    'notifications': notifications,
}

您可以查看文档here

【讨论】:

    【解决方案2】:

    您做错的第一件事是使用字典中的值在模板中呈现。 而是使用密钥,所以你的代码应该是:

    {% for notification in notify %} 
    {% if notification.NOTIFICATION_TYPES == "New Comment" %}
    
    @{{ notification.sender}}You have received new commnet 
          <p>{{ notification.text_preview }}</p>
    {%endif%}
    {%endfor%}
    

    【讨论】:

    • 这不是解决方案。我在发布问题之前尝试过这个
    • 类中的变量日期和您视图中的 order_by 日期也不匹配。
    • 可能这并不能解决问题,但这是您必须解决的问题之一,否则您将无法在模板中呈现数据。
    • Farhan_Ahmed,听着,伙计,不管他是否尝试过天气,无论他提到的代码中是否不正确,至少他会得到纠正。你从不使用值来渲染模板,你总是使用键。所以根据我的回复,至少他会纠正一些问题,可能还有其他一些需要调试的问题。
    • +1,这个答案是正确的。我认为 OP 对他的 if 语句有一些问题。这就是内容没有显示的原因,他认为这个答案不正确。
    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    相关资源
    最近更新 更多