我有一些东西在设置。py,我想能够从模板访问,但我不知道如何做到这一点。我已经试过了

{{CONSTANT_NAME}}

但这似乎并不奏效。这可能吗?


当前回答

将这段代码添加到名为context_processors.py的文件中:

from django.conf import settings as django_settings


def settings(request):
    return {
        'settings': django_settings,
    }

然后,在你的设置文件中,包括一个路径,如'speed .core.base.context_processors。在TEMPLATES中的context_processors设置中的settings'(包含你的应用程序名称和路径)。

(例如,你可以看到settings/base.py和context_processors.py)。

然后可以在任何模板代码中使用特定的设置。例如:

{% if settings.SITE_ID == settings.SPEEDY_MATCH_SITE_ID %}

更新:上面的代码向模板公开了所有设置,包括敏感信息,如SECRET_KEY。黑客可能滥用此特性在模板中显示此类信息。如果你只想将特定的设置暴露给模板,请使用下面的代码:

def settings(request):
    settings_in_templates = {}
    for attr in ["SITE_ID", ...]: # Write here the settings you want to expose to the templates.
        if (hasattr(django_settings, attr)):
            settings_in_templates[attr] = getattr(django_settings, attr)
    return {
        'settings': settings_in_templates,
    }

其他回答

我发现最简单的方法是一个自定义模板标签:

from django import template
from django.conf import settings

register = template.Library()

# settings value
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")

用法:

{% settings_value "LANGUAGE_CODE" %}

IanSR和bchhun都建议在设置中覆盖TEMPLATE_CONTEXT_PROCESSORS。请注意,这个设置有一个默认值,如果在不重新设置默认值的情况下重写它,可能会导致一些问题。在最近的Django版本中,默认值也发生了变化。

https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors

默认的TEMPLATE_CONTEXT_PROCESSORS:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages")

我喜欢Berislav的解决方案,因为在简单的网站上,它干净有效。我不喜欢的是随意地暴露所有的设置常数。所以我最后是这样做的:

from django import template
from django.conf import settings

register = template.Library()

ALLOWABLE_VALUES = ("CONSTANT_NAME_1", "CONSTANT_NAME_2",)

# settings value
@register.simple_tag
def settings_value(name):
    if name in ALLOWABLE_VALUES:
        return getattr(settings, name, '')
    return ''

用法:

{% settings_value "CONSTANT_NAME_1" %}

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:

这个标记将一些settings.py变量值赋给模板的变量:

用法:{% get_settings_value template_var "SETTINGS_VAR" %}

应用程序/ templatetags / my_custom_tags.py:

from django import template
from django.conf import settings

register = template.Library()

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def render(self, context):
        context[self.name] = getattr(settings, self.value.resolve(context, True), "")
        return ''

@register.tag('get_settings_value')
def do_assign(parser, token):
    bits = token.split_contents()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

你的模板:

{% load my_custom_tags %}

# Set local template variable:
{% get_settings_value settings_debug "DEBUG" %}

# Output settings_debug variable:
{{ settings_debug }}

# Use variable in if statement:
{% if settings_debug %}
... do something ...
{% else %}
... do other stuff ...
{% endif %}

查看Django如何创建自定义模板标签的文档:https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

如果你希望每个请求和模板都有一个值,那么使用上下文处理器更合适。

方法如下:

Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context: 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} add your context processor to your settings.py file: TEMPLATES = [{ # whatever comes before 'OPTIONS': { 'context_processors': [ # whatever comes before "your_app.context_processors.admin_media", ], } }] Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically: from django.shortcuts import render def my_view(request): return render(request, "index.html") and finally, in your template: ... <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a> ...