我在django(1.11)上编写自己的自定义context_processor
,并从auth0获取经过身份验证的用户的信息。这不是我第一次写它,我不明白这个错误来自哪里:
ImportError:模块“auth.context_processors”未定义“auth0_processors”属性/类
这是它的样子:
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', {})
任何的想法?
代替
'auth.context_processors.auth0_processors'
给出具体方法:
'auth.context_processors.auth0_processors.auth0_user'
至少这是错误抱怨的:
没有定义“auth0_processors”属性/类
它正在寻找类或属性,因此请尝试使用函数名称。
context_processors选项是一个可调用的列表 - 称为上下文处理器 - 它将请求对象作为其参数,并返回要合并到上下文中的项的字典。
在回答你的评论时:
如果您总是需要相同的对象,那么只需创建一个方法,将所有必需的对象添加到上下文而不是几个方法。
编辑:
另请注意,使用'django.template.context_processors.request'
,您可能已在上下文中拥有完整的request
对象。如果您只需要访问会话,则可能不需要自己的上下文处理器。