【问题标题】:Scope of dictionary passed in render_to_responserender_to_response 中传入的字典范围
【发布时间】:2014-08-22 03:37:59
【问题描述】:
def func(user):
    templatename="login.html"
    return render_to_response(templatename,{'user':user},context_instance=RequestContext(request)

在 django 的 render_to_response 函数中传递的 字典范围 是什么?意味着我们只能在 login.html 模板或我们应用的任何模板中使用该字典。

【问题讨论】:

    标签: python django render-to-response


    【解决方案1】:

    您的dict 的范围仅在login.html 内。

    如果您想在模板中使用对 user 的访问权限,请使用以下内容:

    {{user}}
    

    如果您想在任何模板中使用具有范围的字典,请使用上下文处理器

    将此添加到您的 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}}

    【讨论】:

    • 那么我们如何在整个应用程序中使用它呢? @levi
    • 如果它是用户以外的东西怎么办。? @levi
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多