def func(user):
templatename="login.html"
return render_to_response(templatename,{'user':user},context_instance=RequestContext(request)
在 django 的 render_to_response 函数中传递的字典的范围是什么?意味着我们只能在 login.html 模板或我们应用程序的任何模板中使用该字典。
def func(user):
templatename="login.html"
return render_to_response(templatename,{'user':user},context_instance=RequestContext(request)
在 django 的 render_to_response 函数中传递的字典的范围是什么?意味着我们只能在 login.html 模板或我们应用程序的任何模板中使用该字典。
你的范围dict
是in login.html
only。
如果您想user
在模板中使用对 的访问,请使用以下内容:
{{user}}
如果您想在任何模板中使用具有范围的 dict,请使用上下文处理器
将此添加到您的 Settings.py
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'utils.custom_context_processors.my_context_processor',
)
在项目根目录中创建一个文件夹,将其命名为“utils”,在该文件夹中创建init .py 文件和 custom_context_processors.py
+apps
....other folders.
+utils
---__init__.py
---custom_context_processors.py
custom_context_processors.py
def my_context_processor(request):
your_custom_dict = {...}
return your_custom_dict
有了它,your_custom_dict
将在任何模板中可用。
注意:如果您只想在任何地方访问用户,只需执行{{request.user}}