首页 > 解决方案 > Django 字典更新序列元素#0 的长度为 0;2 是必需的

问题描述

在我的上下文处理器中传递这行代码后,我遇到了错误'notifications.views.Count_Notifications,我正面临未经身份验证的用户的这个问题。我在上下文处理器中传递上下文,以便在我的 base.html 导航栏中显示一些用户信息,例如通知数量、用户名等。这是我的代码:

视图.py

@login_required
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}

设置.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            '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'
            ],
        },
    },
]

控制台错误

updates.update(processor(self.request))
ValueError: dictionary update sequence element #0 has length 0; 2 is required
[18/Jul/2021 01:03:04] "GET / HTTP/1.1" 500 99622

标签: pythondjango

解决方案


如果您使用@login_required,并且用户未通过身份验证,那么它将返回HttpResponseRedirect[Django-doc],而不是空字典。

因此,您需要在上下文处理器中检查身份验证,因此:

# no login_required
def Count_Notifications(request):
    count_notifications_comment = 0
    count_notifications_author = 0
    blog_author = None
    if request.user.is_authenticated:
        blog_author = Blog.objects.filter(author=request.user)
        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
    }

推荐阅读