Django dictionary update sequence element #0 has length 0; 2 is required

Viewed 664

after passing this line of code in my context processor I am getting above error 'notifications.views.Count_Notifications I am facing this problems for unauthenticated user. I am passing context in context processor for showing few user info in my base.html navbar such as number of notifications, user name etc. here is my code:

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'
            ],
        },
    },
]

console error

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
1 Answers

If you use @login_required, and the user is not authenticated, then it will return a HttpResponseRedirect [Django-doc], not an empty dictionary.

You will thus need to check authentication in your context processor, so:

# 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
    }
Related