简体   繁体   中英

django writing custom context processor

I'm writing my own custom context_processor on django (1.11) and to get infos of an authenticated user from auth0. It's not my first time writing it and I don't understand where this error comes from :

ImportError : Module "auth.context_processors" does not define a "auth0_processors" attribute/class

Here's what it looks like :

auth/settings.py :

'context_processors': [
     'django.template.context_processors.debug',
     'django.template.context_processors.request',
     'django.contrib.auth.context_processors.auth',
     'django.contrib.messages.context_processors.messages',
     'auth.context_processors.auth0_processors', 
],

auth/context_processors/auth0_processors.py :

def auth0_user(request):
    try:
        user = request.session['profile']
    except Exception as e:
        user = None

    return {'auth0_user': user}

accounts/views.py :

def home(request):
    return render(request, 'home.html', {})

Any idea?

Instead of

'auth.context_processors.auth0_processors'

give the concrete method:

'auth.context_processors.auth0_processors.auth0_user'

At least that is what the error is complaining about:

does not define a "auth0_processors" attribute/class

It is looking for a class or attribute, so try with the function name.

From the documentation :

The context_processors option is a list of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context.

In answer to your comment:

If you always need the same objects then just create one method that adds all of the required objects to the context instead of several methods.

EDIT:

Also note that with 'django.template.context_processors.request' you could already have the complete request object in the context. You might not need your own context processor if you just need access to the session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM