Context processor for templates | ValueError - Django

0

Very good friends, I have my custom context processor, so that it can be used in all the django project templates in the form of a variable:

{{ u_model }}

This is my context processor:

proccesors.py

from django.contrib.auth.decorators import login_required

@login_required(redirect_field_name='login')
def ctx_dict(request):
    u_model = Model.objects.all().filter(user=request.user)
    ctx = {
        'u_model':u_model, 
    }
    return ctx

This added in settings as it should be:

settings.py

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    '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',
            'my_app.proccesors.ctx_dict',
            ],
        },
    },
]

template.html

{% if request.user.is_authenticated %}
    {% for x in u_model %}
        {{ x.atributo }}  # Es un campo de mi modelo Model
    {% endfor  %}
{% else %}
     No logueado
{% endif %} 

Everything works correctly when the user is logged in, but when he closes his session I see the following error:

  

ValueError: dictionary update sequence element # 0 has length 0; 1 is required

Then I do not know what is due. Thank you very much friends.

    
asked by Yamamoto AY 17.09.2018 в 22:11
source

2 answers

1
def ctx_dict(request):
    if request.user.is_authenticated:
        u_model = Model.objects.filter(user=request.user)
        ctx = {
              'u_model':u_model, 
        }
    else:
       ctx = {}
return ctx

Do it like this, remove the decorator because if you have valid login or not, the .all() is only used if you are going to return all records if you use .filter() is not necessary.

    
answered by 19.09.2018 / 09:24
source
1

What I think is happening is that you do not give value to u_model in case the user is not logged in. In that case you send a dictionary with a key but no value. Hence the error.

There are several ways to solve it, for example, verify before the user is logged in.

from django.contrib.auth.decorators import login_required

@login_required(redirect_field_name='login')
def ctx_dict(request):
    if request.user.is_authenticated:
        u_model = Model.objects.all().filter(user=request.user)
        ctx = {
            'u_model':u_model, 
             }
    else:
        ctx = {}
    return ctx
    
answered by 18.09.2018 в 09:39