【发布时间】:2021-07-18 03:28:36
【问题描述】:
在我的上下文处理器中传递这行代码后,我遇到了错误'notifications.views.Count_Notifications 我正面临未经身份验证的用户的这个问题。我在上下文处理器中传递上下文,以便在我的 base.html 导航栏中显示一些用户信息,例如通知数量、用户名等。这是我的代码:
views.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}
settings.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
【问题讨论】:
-
如果你放弃
@login_required怎么办? -
Willem Van Onsem 收到此错误
AnonymousUser' object is not iterable如果删除 @login_required -
这意味着
request.user没有被认证,但是你不能使用login_required,这样它就会返回一个HTTP重定向对象,而不是一个空字典。 -
Willem Van Onsem 那么我将如何在我的 bas.html 导航栏中显示用户信息,例如通知数量、用户名等。我需要在我的 base.html 中传递上下文以显示登录用户信息在导航栏中。
-
如果用户没有登录,那么显示一些通知是没有意义的。