簡體   English   中英

在上下文處理器中傳遞用戶上下文后,Django 'AnonymousUser' 對象不可迭代

[英]Django 'AnonymousUser' object is not iterable after passing user context in context processor

我需要在我的導航欄中顯示一些用戶信息,例如通知數量、用戶名等。所以我在我的上下文處理器中傳遞上下文。 我的導航欄位於我的 base.htm 中,我正在我的所有 html 頁面中擴展我的 base.html。 如果用戶未登錄'AnonymousUser' object is not iterable我會收到此錯誤。這是我的代碼:

設置.py

 'context_processors': 
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'notifications.views.Count_Notifications', #passing context from notifications app

視圖.py

def Count_Notifications(request):
    count_notifications_comment = 0
    count_notifications_author = 0
    blog_author = Blog.objects.filter(author=request.user)
    if request.user.is_authenticated:
        count_notifications_comment = Notifications.objects.filter(sender=request.user,is_seen=False).count()
        count_notifications_author = Notifications.objects.filter(user=request.user,is_seen_author_noti=False).count()
    return {'count_notifications_comment':count_notifications_comment,'count_notifications_author':count_notifications_author,'blog_author':blog_author} 

控制台錯誤:

raise ValueError(
ValueError: Cannot assign "False": "Notifications.user" must be a "User" instance.
[17/Jul/2021 02:18:08] "POST /admin/blog/blog/26/change/ HTTP/1.1" 500 160786

在您的視圖上方添加需要登錄的裝飾器,以便您在訪問此頁面之前進行連接

從 django.contrib.auth.decorators 導入 login_required

@login_required def Count_Notifications(request): .....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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