我有一些东西在设置。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>
...

其他回答

我稍微改进了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块中使用。

如果有人像我一样发现了这个问题,那么我将发布我的解决方案,它适用于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/

对于那些想要使用@Berislav的方法(自定义模板标签)和if标签的人:

/ app / templatetags / my_settings.py:

from django import template
from django.conf import settings

register = template.Library()

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

模板文件:

<!-- Load your tags -->
{% load my_settings %}
{% settings_value 'ENABLE_FEATURE_A' as ENABLE_FEATURE_A %}

{% if ENABLE_FEATURE_A %}
<!-- Feature A stuffs -->
{% endif %}

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

方法如下:

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

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")