python - 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
解决方案
如果您使用@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
}
推荐阅读
- javascript - NGRX:创建多个reducer 响应的“全局”操作的正确方法是什么?
- c# - WPF:使用 MVVM 的 SelectAll \ UnSelectAll
- mysql - MySQL使用while循环插入多行函数
- opencv - 使用opencv进行外在矩阵计算
- r - 如何在get函数中定义一个序列?
- typo3 - TYPO3 v9:如何查询额外的外部数据库(MSSQL)
- python - Flask / SQLAlchemy - 请求具有多对多关系的表
- javascript - 一种解析 tmTheme 文件以获取设置的方法?
- java - 在 Java android studio 中解析 json
- url - 如何使用&符号链接到内部链接?