[英]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. 我正在Django(1.11)上编写自己的自定义
context_processor
,并从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
ImportError:模块“ auth.context_processors”未定义“ auth0_processors”属性/类
Here's what it looks like : 看起来是这样的:
auth/settings.py : 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 : 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 : account / 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
没有定义“ auth0_processors” 属性/类
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.
context_processors选项是可调用项的列表,称为上下文处理器 ,这些可调用项将请求对象作为其自变量,并返回要合并到上下文中的项的字典。
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. 还要注意,使用
'django.template.context_processors.request'
您可能已经在上下文中拥有了完整的request
对象。 You might not need your own context processor if you just need access to the session. 如果只需要访问会话,则可能不需要自己的上下文处理器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.