我希望能够从模板访问 settings.py 中的一些内容,但我不知道该怎么做。我已经试过了
{{CONSTANT_NAME}}
但这似乎行不通。这可能吗?
最佳答案
如果这是您希望每个请求和模板都具有的值,请使用 context processor比较合适。
方法如下:
在您的应用程序目录中创建一个
context_processors.py
文件。假设我想在每个上下文中都有ADMIN_PREFIX_VALUE
值:from django.conf import settings # import the settings file def admin_media(request): # return the value you want as a dictionnary. you may add multiple values in there. return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
将您的上下文处理器添加到您的settings.py 文件中:
TEMPLATES = [{ # whatever comes before 'OPTIONS': { 'context_processors': [ # whatever comes before "your_app.context_processors.admin_media", ], } }]
在您的 View 中使用
RequestContext
将您的上下文处理器添加到您的模板中。render
shortcut自动执行此操作:from django.shortcuts import render def my_view(request): return render(request, "index.html")
最后,在您的模板中:
... <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a> ...
关于django - 我可以从 Django 的模板访问 settings.py 中的常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/433162/