Can I access constants in settings.py from templat

2019-01-02 16:44发布

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?

15条回答
明月照影归
2楼-- · 2019-01-02 17:00

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.

查看更多
墨雨无痕
3楼-- · 2019-01-02 17:01

I find the simplest approach being a single 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" %}
查看更多
弹指情弦暗扣
4楼-- · 2019-01-02 17:04

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.

查看更多
孤独寂梦人
5楼-- · 2019-01-02 17:04

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 https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/settings/base.py and https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/base/context_processors.py).

查看更多
长期被迫恋爱
6楼-- · 2019-01-02 17:08

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

查看更多
深知你不懂我心
7楼-- · 2019-01-02 17:08

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 }}
查看更多
登录 后发表回答