我可以从 Django 中的模板访问 settings.py 中的常量吗?

发布于 2024-07-11 19:07:34 字数 136 浏览 11 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

最终幸福 2024-07-18 19:07:34

如果这是您希望每个请求都具有的值 模板,使用上下文处理器 更合适。

操作方法如下:

  1. 在应用目录中创建一个 context_processors.py 文件。 假设我想在每个上下文中都有 ADMIN_PREFIX_VALUE 值:

    from django.conf import settings #导入设置文件 
    
      def admin_media(请求): 
          # 以字典形式返回你想要的值。   您可以在其中添加多个值。 
          返回 {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX} 
      
  2. 将上下文处理器添加到您的 settings.py 文件中:

    模板 = [{ 
          # 前面的内容 
          '选项': { 
              '上下文处理器':[ 
                  # 前面的内容 
                  “your_app.context_processors.admin_media”, 
              ], 
          } 
      }] 
      
  3. 在视图中使用 RequestContext 在模板中添加上下文处理器。 render 快捷方式 可以执行此操作自动:

    from django.shortcuts import render 
    
      def my_view(请求): 
          返回渲染(请求,“index.html”) 
      
  4. 最后,在您的模板中:

    <前><代码>...
    管理媒体路径
    ...

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. 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}
    
  2. 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",
            ],
        }
    }]
    
  3. 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")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    
慵挽 2024-07-18 19:07:34

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

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

I find the simplest approach being a single custom template tag:

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

Usage:

{% settings_value "LANGUAGE_CODE" %}
青丝拂面 2024-07-18 19:07:34

如果您使用 Django 内置的通用视图或在render_to_response 快捷函数。 以下是每种情况的示例:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template

def my_generic_view(request, template='my_template.html'):
    return direct_to_template(request, template)

def more_custom_view(request, template='my_template.html'):
    return render_to_response(template, {}, context_instance=RequestContext(request))

这些视图都有几个常用的设置,例如可用于模板的 settings.MEDIA_URL 等。

如果您正在寻找对设置中其他常量的访问,然后只需解压所需的常量并将它们添加到您在视图函数中使用的上下文字典中,如下所示:

from django.conf import settings
from django.shortcuts import render_to_response

def my_view_function(request, template='my_template.html'):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render_to_response(template, context)

现在您可以访问 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 the render_to_response shortcut function. Here's an example of each case:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic.simple import direct_to_template

def my_generic_view(request, template='my_template.html'):
    return direct_to_template(request, template)

def more_custom_view(request, template='my_template.html'):
    return render_to_response(template, {}, context_instance=RequestContext(request))

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:

from django.conf import settings
from django.shortcuts import render_to_response

def my_view_function(request, template='my_template.html'):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render_to_response(template, context)

Now you can access settings.FAVORITE_COLOR on your template as {{ favorite_color }}.

渡你暖光 2024-07-18 19:07:34

查看 django-settings-export (免责声明:我'我是这个项目的作者)。

例如...

$ pip install django-settings-export

settings.py

TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'django_settings_export.settings_export',
            ],
        },
    },
]

MY_CHEESE = 'Camembert';

SETTINGS_EXPORT = [
    'MY_CHEESE',
]

template.html

<script>var MY_CHEESE = '{{ settings.MY_CHEESE }}';</script>

Check out django-settings-export (disclaimer: I'm the author of this project).

For example...

$ pip install django-settings-export

settings.py

TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'django_settings_export.settings_export',
            ],
        },
    },
]

MY_CHEESE = 'Camembert';

SETTINGS_EXPORT = [
    'MY_CHEESE',
]

template.html

<script>var MY_CHEESE = '{{ settings.MY_CHEESE }}';</script>
陪你搞怪i 2024-07-18 19:07:34

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

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

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

Another way to do this is to create a custom template tag which can let you fish values out of the settings.

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

You can then use:

{% value_from_settings "FQDN" %}

to print it on any page, without jumping through context-processor hoops.

爱你是孤单的心事 2024-07-18 19:07:34

我喜欢 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" %}

这可以保护您未命名的任何常量在模板中使用,如果您想要真正喜欢,您可以在设置中设置一个元组,并创建多个模板为不同的页面、应用程序或区域添加标签,只需根据需要将本地元组与设置元组组合起来,然后进行列表理解以查看该值是否可接受。
我同意,在一个复杂的网站上,这有点简单化,但是有些值在模板中通用会很好,而且这似乎工作得很好。
感谢贝里斯拉夫的原创想法!

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:

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

Usage:

{% 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!

甜点 2024-07-18 19:07:34

使用 Django 2.0+ 添加包含创建自定义模板标记以解决此问题的完整说明的答案

在您的应用文件夹中,创建一个名为 templatetags 的文件夹。 在其中创建 __init__.pycustom_tags.py

自定义标签文件夹结构

custom_tags.py中创建自定义标签函数提供对 settings 常量中任意键的访问:

from django import template
from django.conf import settings

register = template.Library()

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

要理解此代码,我建议阅读 Django 文档中有关简单标签的部分

然后,您需要通过在您将使用它的任何模板中加载此文件来使 Django 意识到此(以及任何其他)自定义标记。 就像您需要加载内置静态标签一样:

{% load custom_tags %}

加载后,它可以像任何其他标签一样使用,只需提供您需要返回的特定设置即可。 因此,如果您的设置中有 BUILD_VERSION 变量:

{% get_setting "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:

Custom tags folder structure

In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:

from django import template
from django.conf import settings

register = template.Library()

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

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:

{% load custom_tags %}

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:

{% get_setting "BUILD_VERSION" %}

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.

不爱素颜 2024-07-18 19:07:34

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

from django.conf import settings as django_settings


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

然后,在您的设置文件中包含一个路径,例如 'speedy.core.base.context_processors.settings' (与您的应用名称和路径)位于 TEMPLATES'context_processors' 设置中。

(您可以查看例如 settings/base .pycontext_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,
    }

Add this code to a file called context_processors.py:

from django.conf import settings as django_settings


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

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

(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:

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

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:

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,
    }
苦妄 2024-07-18 19:07:34

我改进了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 块中使用变得很容易。

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

You can use this tag in your Template via:

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

or via

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

The advantage of the as ... notation is that this makes it easy to use in blocktrans blocks via a simple {{my_fqdn}}.

入怼 2024-07-18 19:07:34

如果使用基于类的视图:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}
掐死时间 2024-07-18 19:07:34

上面来自 bchhun 的示例很好,只是您需要从 settings.py 显式构建上下文字典。 下面是一个未经测试的示例,说明如何从 settings.py 的所有大写属性自动构建上下文字典(回复:“^[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',
...
)

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:

_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',
...
)
安人多梦 2024-07-18 19:07:34

如果有人像我一样发现这个问题,那么我将发布适用于 Django 2.0 的解决方案:

此标记将一些 settings.py 变量值分配给模板的变量:

用法: {% get_settings_value template_var "SETTINGS_VAR" %}< /code>

app/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/

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:

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)

Your template:

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

See Django's documentation how to create custom template tags here: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/

草莓味的萝莉 2024-07-18 19:07:34

对于那些想要使用 @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 %}

For those who want to use @Berislav's approach (custom template tag) with if tag:

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

Template file:

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

{% if ENABLE_FEATURE_A %}
<!-- Feature A stuffs -->
{% endif %}
断爱 2024-07-18 19:07:34

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

  1. views.py

    从 local_settings 导入 BASE_URL 
    
      def 根(请求): 
          返回 render_to_response('hero.html', {'BASE_URL': BASE_URL}) 
      
  2. hero.html

    var BASE_URL = '{{ JS_BASE_URL }}'; 
      

I found this to be the simplest approach for Django 1.3:

  1. views.py

    from local_settings import BASE_URL
    
    def root(request):
        return render_to_response('hero.html', {'BASE_URL': BASE_URL})
    
  2. hero.html

    var BASE_URL = '{{ JS_BASE_URL }}';
    
扎心 2024-07-18 19:07:34

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

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 :

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")
蓝眼睛不忧郁 2024-07-18 19:07:34

如果我们要在单个变量上比较上下文与模板标签,那么了解更有效的选项可能是有益的。 但是,您可能最好仅从需要该变量的模板中深入了解设置。 在这种情况下,将变量传递到所有模板中是没有意义的。 但是,如果您将变量发送到通用模板(例如 base.html 模板)中,那么这并不重要,因为 base.html 模板会在每个请求上呈现,因此您可以使用任一方法。

如果您决定使用模板标签选项,请使用以下代码,因为它允许您传递默认值,以防相关变量未定义。

示例: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)

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

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)
絕版丫頭 2024-07-18 19:07:34

更完整的实施。

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

A more complete implementation.

/project/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>
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文