简体   繁体   中英

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. I am not understanding where I am doing mistake.here is my code:

notifications 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%}

why notification content not showing in my html template? 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'

context = {
    'notify': notifications,
}

So in your views.py , you can change 'notify' to 'notifications' :

context = {
    'notifications': notifications,
}

You can see document here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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