pythondjangobackend

Value error dictionary update sequence element #0 has length 1; 2 is required


I want to write a context processor, so that the list can be seen anywhere in the application in django (version 2.1). I'm getting an error:

ValueError at /

dictionary update sequence element #0 has length 1; 2 is required
def following_issues(request):
    request_context = RequestContext(request)
    request_context.push({'following_issues': Issue.objects.filter(followers=request.user.is_authenticated)})
    return request_context

In my settings:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.template.context_processors.debug',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'base.context_processors.following_issues',
            ],
        },
    },
]

Solution

  • I think you misunderstood how to write a context processor. As the documentation [Django-doc] says:

    A context processor has a very simple interface: It's a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.

    So you should simply write this as:

    def following_issues(request):
        if request.user.is_authenticated:
            return {
                'following_topics': Issue.objects.filter(followers=request.user)
            }
        else:
            return {
                'following_topics': Issue.objects.none()
            }

    We thus can simply return a dictionary here where we map following_topics on Issue.objects.filter(..) expression.

    Furthermore you can not specify followers=request.user.is_authenticated, since that is a boolean, and you probably, given I understand the modeling correctly, filter on the user. Here I wrote that in case the user is not authenticated, we return an empty QuerySet.