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

{{CONSTANT_NAME}}

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


当前回答

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

方法如下:

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> ...

其他回答

一个更完整的实现。

/项目/ settings.py

APP_NAME = 'APP'

- app - templatetags settings_value . py

from django import template
from django.conf import settings
 
register = template.Library()
 
@register.simple_tag
def settings_value(name):
    return getattr(settings, name, "")

/app/templates/index.html

<!DOCTYPE html>
{% load static %}
{% load settings_value %}
<head>
    <title>{% settings_value "APP_NAME" %}</title>
...

另一种方法是创建一个自定义模板标签,它可以让您从设置中获取值。

@register.tag
def value_from_settings(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, var = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return ValueFromSettings(var)

class ValueFromSettings(template.Node):
    def __init__(self, var):
        self.arg = template.Variable(var)
    def render(self, context):        
        return settings.__getattr__(str(self.arg))

然后你可以使用:

{% value_from_settings "FQDN" %}

将它打印在任何页面上,而无需跳过上下文处理器的约束。

上面来自bchhun的例子很好,只是你需要从settings.py显式地构建上下文字典。下面是一个未经测试的示例,说明如何从settings.py的所有大写属性(re: "^[A-Z0-9_]+$")自动构建上下文字典。

在settings.py的末尾:

_context = {} 
local_context = locals()
for (k,v) in local_context.items():
    if re.search('^[A-Z0-9_]+$',k):
        _context[k] = str(v)

def settings_context(context):
    return _context

TEMPLATE_CONTEXT_PROCESSORS = (
...
'myproject.settings.settings_context',
...
)

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.

如果您决定使用template tags选项,那么使用下面的代码,因为它允许您传入一个默认值,以防有问题的变量未定义。

例如:get_from_settings my_variable as my_context_value

例如:get_from_settings my_variable my_default as my_context_value

class SettingsAttrNode(Node):
    def __init__(self, variable, default, as_value):
        self.variable = getattr(settings, variable, default)
        self.cxtname = as_value

    def render(self, context):
        context[self.cxtname] = self.variable
        return ''


def get_from_setting(parser, token):
    as_value = variable = default = ''
    bits = token.contents.split()
    if len(bits) == 4 and bits[2] == 'as':
        variable = bits[1]
        as_value = bits[3]
    elif len(bits) == 5 and bits[3] == 'as':
        variable     = bits[1]
        default  = bits[2]
        as_value = bits[4]
    else:
        raise TemplateSyntaxError, "usage: get_from_settings variable default as value " \
                "OR: get_from_settings variable as value"

    return SettingsAttrNode(variable=variable, default=default, as_value=as_value)

get_from_setting = register.tag(get_from_setting)

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

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" %}