我可以从 Django 中的模板访问 settings.py 中的常量吗?
我在 settings.py 中有一些东西,我希望能够从模板访问它们,但我不知道如何做到这一点。 我已经尝试过了
{{CONSTANT_NAME}}
,但这似乎不起作用。 这可能吗?
I have some stuff in settings.py that I'd like to be able to access from a template, but I can't figure out how to do it. I already tried
{{CONSTANT_NAME}}
but that doesn't seem to work. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
如果这是您希望每个请求都具有的值 模板,使用上下文处理器 更合适。
操作方法如下:
在应用目录中创建一个
context_processors.py
文件。 假设我想在每个上下文中都有ADMIN_PREFIX_VALUE
值:将上下文处理器添加到您的 settings.py 文件中:
在视图中使用
RequestContext
在模板中添加上下文处理器。render
快捷方式 可以执行此操作自动:最后,在您的模板中:
<前><代码>...
管理媒体路径
...
If it's a value you'd like to have for every request & template, using a context processor is more appropriate.
Here's how:
Make a
context_processors.py
file in your app directory. Let's say I want to have theADMIN_PREFIX_VALUE
value in every context:add your context processor to your settings.py file:
Use
RequestContext
in your view to add your context processors in your template. Therender
shortcut does this automatically:and finally, in your template:
我发现最简单的方法是单个 自定义模板标签:
用法:
I find the simplest approach being a single custom template tag:
Usage:
如果您使用 Django 内置的通用视图或在
render_to_response
快捷函数。 以下是每种情况的示例:这些视图都有几个常用的设置,例如可用于模板的
settings.MEDIA_URL
等。如果您正在寻找对设置中其他常量的访问,然后只需解压所需的常量并将它们添加到您在视图函数中使用的上下文字典中,如下所示:
现在您可以访问
settings.FAVORITE_COLOR
在您的模板上为{{ favorite_color }}
。Django provides access to certain, frequently-used settings constants to the template such as
settings.MEDIA_URL
and some of the language settings if you use django's built in generic views or pass in a context instance keyword argument in therender_to_response
shortcut function. Here's an example of each case:These views will both have several frequently used settings like
settings.MEDIA_URL
available to the template as{{ MEDIA_URL }}
, etc.If you're looking for access to other constants in the settings, then simply unpack the constants you want and add them to the context dictionary you're using in your view function, like so:
Now you can access
settings.FAVORITE_COLOR
on your template as{{ favorite_color }}
.查看
django-settings-export
(免责声明:我'我是这个项目的作者)。例如...
settings.py
template.html
Check out
django-settings-export
(disclaimer: I'm the author of this project).For example...
settings.py
template.html
另一种方法是创建一个自定义模板标签,它可以让您从设置中获取值。
然后,您可以使用:
将其打印在任何页面上,而无需跳过上下文处理器。
Another way to do this is to create a custom template tag which can let you fish values out of the settings.
You can then use:
to print it on any page, without jumping through context-processor hoops.
我喜欢 Berislav 的解决方案,因为在简单的网站上,它干净有效。 我不喜欢的是随意暴露所有设置常量。 所以我最终做的是这样的:
用法:
这可以保护您未命名的任何常量在模板中使用,如果您想要真正喜欢,您可以在设置中设置一个元组,并创建多个模板为不同的页面、应用程序或区域添加标签,只需根据需要将本地元组与设置元组组合起来,然后进行列表理解以查看该值是否可接受。
我同意,在一个复杂的网站上,这有点简单化,但是有些值在模板中通用会很好,而且这似乎工作得很好。
感谢贝里斯拉夫的原创想法!
I like Berislav's solution, because on simple sites, it is clean and effective. What I do NOT like is exposing all the settings constants willy-nilly. So what I ended up doing was this:
Usage:
This protects any constants that you have not named from use in the template, and if you wanted to get really fancy, you could set a tuple in the settings, and create more than one template tag for different pages, apps or areas, and simply combine a local tuple with the settings tuple as needed, then do the list comprehension to see if the value is acceptable.
I agree, on a complex site, this is a bit simplistic, but there are values that would be nice to have universally in templates, and this seems to work nicely.
Thanks to Berislav for the original idea!
使用 Django 2.0+ 添加包含创建自定义模板标记以解决此问题的完整说明的答案
在您的应用文件夹中,创建一个名为 templatetags 的文件夹。 在其中创建 __init__.py 和 custom_tags.py:
在custom_tags.py中创建自定义标签函数提供对 settings 常量中任意键的访问:
要理解此代码,我建议阅读 Django 文档中有关简单标签的部分。
然后,您需要通过在您将使用它的任何模板中加载此文件来使 Django 意识到此(以及任何其他)自定义标记。 就像您需要加载内置静态标签一样:
加载后,它可以像任何其他标签一样使用,只需提供您需要返回的特定设置即可。 因此,如果您的设置中有 BUILD_VERSION 变量:
此解决方案不适用于数组,但如果您需要,您可能会在模板中添加很多逻辑。
注意:更干净、更安全的解决方案可能是创建一个自定义上下文处理器,您可以在其中将所需的设置添加到所有模板可用的上下文中。 这样您就可以降低在模板中错误输出敏感设置的风险。
Adding an answer with complete instructions for creating a custom template tag that solves this, with Django 2.0+
In your app-folder, create a folder called templatetags. In it, create __init__.py and custom_tags.py:
In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:
To understand this code I recommend reading the section on simple tags in the Django docs.
Then, you need to make Django aware of this (and any additional) custom tag by loading this file in any template where you will use it. Just like you need to load the built in static tag:
With it loaded it can be used just like any other tag, just supply the specific setting you need returned. So if you have a BUILD_VERSION variable in your settings:
This solution will not work with arrays, but if you need that you might be putting to much logic in your templates.
Note: A more clean and failsafe solution would probably be to make a custom context processor where you add the settings you need to a context available to all templates. This way you reduce the risk of outputting sensitive settings in your templates by mistake.
将此代码添加到名为
context_processors.py
的文件中:然后,在您的设置文件中包含一个路径,例如
'speedy.core.base.context_processors.settings'
(与您的应用名称和路径)位于TEMPLATES
的'context_processors'
设置中。(您可以查看例如 settings/base .py 和 context_processors。 py)。
然后您可以在任何模板代码中使用特定设置。 例如:
更新:上面的代码将所有设置公开给模板,包括敏感信息,例如您的
SECRET_KEY
。 黑客可能会滥用此功能在模板中显示此类信息。 如果您只想向模板公开特定设置,请改用以下代码:Add this code to a file called
context_processors.py
:And then, in your settings file, include a path such as
'speedy.core.base.context_processors.settings'
(with your app name and path) in the'context_processors'
settings inTEMPLATES
.(You can see for example settings/base.py and context_processors.py).
Then you can use the specific setting in any template code. For example:
Update: The code above exposes all the settings to templates, including sensitive information such as your
SECRET_KEY
. A hacker might abuse this feature to display such information in the templates. If you want to expose only specific settings to the templates, use this code instead:我改进了chrisdew的答案 (创建您自己的标签)一点点。
首先,创建文件
yourapp/templatetags/value_from_settings.py
,在其中定义您自己的新标签value_from_settings
:您可以通过以下方式在模板中使用此标签:
或
通过
as ...
表示法的特点是,这使得通过简单的{{my_fqdn}}
在blocktrans
块中使用变得很容易。I improved chrisdew's answer (to create your own tag) a little bit.
First, create the file
yourapp/templatetags/value_from_settings.py
in which you define your own new tagvalue_from_settings
:You can use this tag in your Template via:
or via
The advantage of the
as ...
notation is that this makes it easy to use inblocktrans
blocks via a simple{{my_fqdn}}
.如果使用基于类的视图:
If using a class-based view:
上面来自 bchhun 的示例很好,只是您需要从 settings.py 显式构建上下文字典。 下面是一个未经测试的示例,说明如何从 settings.py 的所有大写属性自动构建上下文字典(回复:“^[A-Z0-9_]+$”)。
在settings.py末尾:
The example above from bchhun is nice except that you need to explicitly build your context dictionary from settings.py. Below is an UNTESTED example of how you could auto-build the context dictionary from all upper-case attributes of settings.py (re: "^[A-Z0-9_]+$").
At the end of settings.py:
如果有人像我一样发现这个问题,那么我将发布适用于 Django 2.0 的解决方案:
此标记将一些 settings.py 变量值分配给模板的变量:
用法:
{% get_settings_value template_var "SETTINGS_VAR" %}< /code>
app/templatetags/my_custom_tags.py:
您的模板:
请参阅 Django 文档,了解如何在此处创建自定义模板标签: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
If someone finds this question like I did, then I'll post my solution which works on Django 2.0:
This tag assigns some settings.py variable value to template's variable:
Usage:
{% get_settings_value template_var "SETTINGS_VAR" %}
app/templatetags/my_custom_tags.py:
Your template:
See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
对于那些想要使用 @Berislav 的方法(自定义模板标签)和
if
标签的人:/app/templatetags/my_settings.py:
模板文件:
For those who want to use @Berislav's approach (custom template tag) with
if
tag:/app/templatetags/my_settings.py:
Template file:
我发现这是 Django 1.3 最简单的方法:
views.py
hero.html
I found this to be the simplest approach for Django 1.3:
views.py
hero.html
IanSR 和 bchhun 都建议覆盖设置中的 TEMPLATE_CONTEXT_PROCESSORS。 请注意,此设置有一个默认值,如果您在不重新设置默认值的情况下覆盖它,可能会导致一些奇怪的事情。 在 Django 的最新版本中,默认值也发生了变化。
https://docs.djangoproject.com/en/1.3/ ref/settings/#template-context-processors
默认的 TEMPLATE_CONTEXT_PROCESSORS :
Both IanSR and bchhun suggested overriding TEMPLATE_CONTEXT_PROCESSORS in the settings. Be aware that this setting has a default that can cause some screwy things if you override it without re-setting the defaults. The defaults have also changed in recent versions of Django.
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
The default TEMPLATE_CONTEXT_PROCESSORS :
如果我们要在单个变量上比较上下文与模板标签,那么了解更有效的选项可能是有益的。 但是,您可能最好仅从需要该变量的模板中深入了解设置。 在这种情况下,将变量传递到所有模板中是没有意义的。 但是,如果您将变量发送到通用模板(例如 base.html 模板)中,那么这并不重要,因为 base.html 模板会在每个请求上呈现,因此您可以使用任一方法。
如果您决定使用模板标签选项,请使用以下代码,因为它允许您传递默认值,以防相关变量未定义。
示例:get_from_settings my_variable as my_context_value
示例:get_from_settings my_variable my_default as my_context_value
If we were to compare context vs. template tags on a single variable, then knowing the more efficient option could be benificial. However, you might be better off to dip into the settings only from templates that need that variable. In that case it doesn't make sense to pass the variable into all templates. But if you are sending the variable into a common template such as the base.html template, Then it would not matter as the base.html template is rendered on every request, so you can use either methods.
If you decide to go with the template tags option, then use the following code as it allows you to pass a default value in, just in case the variable in-question was undefined.
Example: get_from_settings my_variable as my_context_value
Example: get_from_settings my_variable my_default as my_context_value
更完整的实施。
/project/settings.py
/app/templatetags/settings_value.py
/app/templates/index.html
A more complete implementation.
/project/settings.py
/app/templatetags/settings_value.py
/app/templates/index.html