python - 如何让某些东西出现在 Django 的每个页面上?

标签 python django

我很好奇处理在每个页面或多个页面上出现某些内容而不必像这样手动将数据分配给每个页面的最佳实践方法:

# views.py

def page0(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )

def page1(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )
...
def page9(request):
    return render_to_response(
        "core/index.html",
        {
            "locality": getCityForm(request.user),
        },
        context_instance=RequestContext(request)
    )

现在我可以想出几种方法来做到这一点,包括编写我自己的 Context 或者可能是一些中间件,当然,在每个页面上复制/粘贴这个 locality 赋值......我'我只是不确定执行此操作的最佳方法。不过,我很确定这不是最后一个。

最佳答案

你想要一个 context processor .它们生成的数据包含在作为 RequestContext 创建的每个上下文中。它们非常适合这个。

结合显示常用事物的基本模板,您可以摆脱大量复制和粘贴代码的需要。

关于python - 如何让某些东西出现在 Django 的每个页面上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1997109/

相关文章:

python - 为什么在 Django View 中使用 Popen 会挂起?

django - Web Application (Django) 典型项目文件夹结构

python - Django 创建应用程序错误

python - 重复提取数组的一部分

python - Django ;使用 ajax 时重定向无法按预期工作

Django - 根据当前页面突出显示导航?

python - 在 PyCharm 中运行测试如何导致 "Model class doesn' t declare an explicit app_label"错误?

python - DRF : router for ViewSet with a foreign-key lookup_field

python - 使用 python 获取股票数据-不使用 quandl

Python 验证错误对象不是 json 可序列化的