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

{{CONSTANT_NAME}}

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


当前回答

一个更完整的实现。

/项目/ 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>
...

其他回答

我发现这是Django 1.3最简单的方法:

views.py 从local_settings导入BASE_URL def根(请求): 返回render_to_response('hero.html', {'BASE_URL': BASE_URL}) hero.html var BASE_URL = '{{JS_BASE_URL}}';

我稍微改进了chrisdew的答案(创建自己的标签)。

首先,创建文件yourapp/templatetags/value_from_settings.py,在其中定义你自己的新标签value_from_settings:

from django.template import TemplateSyntaxError, Variable, Node, Variable, Library
from yourapp import settings

register = Library()
# I found some tricks in URLNode and url from defaulttags.py:
# https://code.djangoproject.com/browser/django/trunk/django/template/defaulttags.py
@register.tag
def value_from_settings(parser, token):
  bits = token.split_contents()
  if len(bits) < 2:
    raise TemplateSyntaxError("'%s' takes at least one " \
      "argument (settings constant to retrieve)" % bits[0])
  settingsvar = bits[1]
  settingsvar = settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar
  asvar = None
  bits = bits[2:]
  if len(bits) >= 2 and bits[-2] == 'as':
    asvar = bits[-1]
    bits = bits[:-2]
  if len(bits):
    raise TemplateSyntaxError("'value_from_settings' didn't recognise " \
      "the arguments '%s'" % ", ".join(bits))
  return ValueFromSettings(settingsvar, asvar)

class ValueFromSettings(Node):
  def __init__(self, settingsvar, asvar):
    self.arg = Variable(settingsvar)
    self.asvar = asvar
  def render(self, context):
    ret_val = getattr(settings,str(self.arg))
    if self.asvar:
      context[self.asvar] = ret_val
      return ''
    else:
      return ret_val

你可以通过以下方式在模板中使用这个标签:

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" %}

或通过

{% load value_from_settings %}
[...]
{% value_from_settings "FQDN" as my_fqdn %}

as的优点是…这使得它很容易通过一个简单的{{my_fqdn}}在blocktrans块中使用。

将这段代码添加到名为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,
    }

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)

上面来自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',
...
)