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
我有一些设置。py,我希望能够从模板访问,但我不知道怎么做。我已经试过
{{CONSTANT_NAME}}
but that doesn't seem to work. Is this possible?
但这似乎行不通。这是可能的吗?
14 个解决方案
#1
155
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:
Django为模板提供了对某些经常使用的设置常量(如设置)的访问。MEDIA_URL和一些语言设置,如果您使用在通用视图中构建的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))
These views will both have several frequently used settings like settings.MEDIA_URL
available to the template as {{ MEDIA_URL }}
, etc.
这些视图都有一些常用的设置,比如设置。该模板可用的MEDIA_URL为{MEDIA_URL},等等。
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 }}
.
现在您可以访问设置。您的模板上的FAVORITE_COLOR是{{FAVORITE_COLOR}}。
#2
371
If it's a value you'd like to have for every request & template, using a context processor is more appropriate.
如果它是您希望为每个请求和模板拥有的值,那么使用上下文处理器就更合适了。
Here's how:
方法如下:
-
Make a
context_processors.py
file in your app directory. Let's say I want to have theADMIN_PREFIX_VALUE
value in every context:context_processors。应用程序目录中的py文件。假设我希望在每个上下文中都有ADMIN_PREFIX_VALUE值:
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:
将上下文处理器添加到设置中。py文件:
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. Therender
shortcut does this automatically:在视图中使用RequestContext来在模板中添加上下文处理器。渲染快捷方式自动完成:
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> ...
#3
219
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
70
Check out django-settings-export
(disclaimer: I'm the author of this project).
查看django- settingsexport(声明:我是这个项目的作者)。
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>
#5
40
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.
要在任何页面上打印它,无需跳过上下文处理器的限制。
#6
22
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:
我喜欢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 ''
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!
这保护任何常数没有命名模板的使用,如果你真的想要的,你可以设置一个元组的设置,并为不同的页面创建一个以上的模板标签,应用程序或区域,并简单地根据需要结合当地的元组和元组的设置,然后列表理解,如果值是可以接受的。我同意,在一个复杂的站点上,这有点过于简单了,但是有一些值可以在模板中普遍使用,这看起来很好。感谢Berislav最初的想法!
#7
11
I improved chrisdew's answer (to create your own tag) a little bit.
我改进了chrisdew的回答(创建自己的标签)。
First, create the file yourapp/templatetags/value_from_settings.py
in which you define your own new tag value_from_settings
:
首先,创建文件yourapp/templatetags/value_from_settings。在其中定义自己的新标签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}}
.
a的优点是……表示法是通过一个简单的{{my_fqdn}}使blocktrans块中使用起来很容易。
#8
7
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_]+$").
上面bchhun的示例很好,只是需要从settings.y显式地构建上下文字典。下面是一个未经测试的示例,说明如何从设置的所有大小写属性自动构建上下文字典。py(re:" ^[A-Z0-9_]+ $”)。
At the end of settings.py:
在结束时。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',
...
)
#9
4
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 }}
#10
3
If someone finds this question like I did, then I'll post my solution which works on Django 2.0:
如果有人像我一样发现了这个问题,我将在Django 2.0上发布我的解决方案:
This tag assigns some settings.py variable value to template's variable:
这个标签分配一些设置。py变量值到模板变量:
Usage: {% get_settings_value template_var "SETTINGS_VAR" %}
用法:{% 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 == True %}
... 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/
参见Django的文档如何在这里创建自定义模板标签:https://docs.djangoproject.com/en/2.0/ howto/customtemplate-tags/。
#11
1
Adding an answer with complete instructions for creating a custom template tag that solves this, with Django 2.0
添加一个完整的说明来创建一个定制模板标签,它可以解决这个问题,Django 2.0。
In your app-folder, create a folder called templatetags. In it, create __init__.py and custom_tags.py:
在app-文件夹中,创建一个名为templatetags的文件夹。,创建__init__。py和custom_tags.py:
In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:
custom_tags。py创建一个自定义标记函数,在设置常量中提供对任意键的访问:
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.
为了理解这段代码,我建议您阅读Django文档中关于简单标记的部分。
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:
然后,您需要通过将该文件加载到将要使用它的任何模板中来让Django了解这个(以及任何其他)自定义标记。就像你需要加载内置的静态标签:
{% 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:
加载后,它可以像其他任何标记一样使用,只需提供需要返回的特定设置。因此,如果在设置中有一个BUILD_VERSION变量:
{% 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.
这个解决方案不能使用数组,但是如果需要的话,您可能需要在模板中加入很多逻辑。
#12
0
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.
IanSR和bchhun都建议在设置中重写template_context_processor。请注意,此设置有一个默认值,如果不重新设置默认值就重写它,可能会导致一些奇怪的事情。在Django的最新版本中,默认值也发生了变化。
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
https://docs.djangoproject.com/en/1.3/ref/settings/ template-context-processors
The default 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")
#13
0
I found this to be the simplest approach for Django 1.3:
我发现这是Django 1.3最简单的方法:
-
views.py
views.py
from local_settings import BASE_URL def root(request): return render_to_response('hero.html', {'BASE_URL': BASE_URL})
-
hero.html
hero.html
var BASE_URL = '{{ JS_BASE_URL }}';
#14
0
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.
如果我们在单个变量上比较上下文和模板标记,那么知道更有效的选项是有益的。但是,最好只从需要该变量的模板中进行设置。在这种情况下,将变量传递给所有模板是没有意义的。但是如果您要将变量发送到一个通用模板(比如base)中。html模板,那么它作为基础就不重要了。每个请求都呈现html模板,因此您可以使用这两种方法。
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
示例:get_from_settings my_variable为my_context_value。
Example: get_from_settings my_variable my_default as my_context_value
示例:get_from_settings my_variable my_default为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)
#1
155
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:
Django为模板提供了对某些经常使用的设置常量(如设置)的访问。MEDIA_URL和一些语言设置,如果您使用在通用视图中构建的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))
These views will both have several frequently used settings like settings.MEDIA_URL
available to the template as {{ MEDIA_URL }}
, etc.
这些视图都有一些常用的设置,比如设置。该模板可用的MEDIA_URL为{MEDIA_URL},等等。
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 }}
.
现在您可以访问设置。您的模板上的FAVORITE_COLOR是{{FAVORITE_COLOR}}。
#2
371
If it's a value you'd like to have for every request & template, using a context processor is more appropriate.
如果它是您希望为每个请求和模板拥有的值,那么使用上下文处理器就更合适了。
Here's how:
方法如下:
-
Make a
context_processors.py
file in your app directory. Let's say I want to have theADMIN_PREFIX_VALUE
value in every context:context_processors。应用程序目录中的py文件。假设我希望在每个上下文中都有ADMIN_PREFIX_VALUE值:
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:
将上下文处理器添加到设置中。py文件:
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. Therender
shortcut does this automatically:在视图中使用RequestContext来在模板中添加上下文处理器。渲染快捷方式自动完成:
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> ...
#3
219
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
70
Check out django-settings-export
(disclaimer: I'm the author of this project).
查看django- settingsexport(声明:我是这个项目的作者)。
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>
#5
40
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.
要在任何页面上打印它,无需跳过上下文处理器的限制。
#6
22
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:
我喜欢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 ''
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!
这保护任何常数没有命名模板的使用,如果你真的想要的,你可以设置一个元组的设置,并为不同的页面创建一个以上的模板标签,应用程序或区域,并简单地根据需要结合当地的元组和元组的设置,然后列表理解,如果值是可以接受的。我同意,在一个复杂的站点上,这有点过于简单了,但是有一些值可以在模板中普遍使用,这看起来很好。感谢Berislav最初的想法!
#7
11
I improved chrisdew's answer (to create your own tag) a little bit.
我改进了chrisdew的回答(创建自己的标签)。
First, create the file yourapp/templatetags/value_from_settings.py
in which you define your own new tag value_from_settings
:
首先,创建文件yourapp/templatetags/value_from_settings。在其中定义自己的新标签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}}
.
a的优点是……表示法是通过一个简单的{{my_fqdn}}使blocktrans块中使用起来很容易。
#8
7
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_]+$").
上面bchhun的示例很好,只是需要从settings.y显式地构建上下文字典。下面是一个未经测试的示例,说明如何从设置的所有大小写属性自动构建上下文字典。py(re:" ^[A-Z0-9_]+ $”)。
At the end of settings.py:
在结束时。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',
...
)
#9
4
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 }}
#10
3
If someone finds this question like I did, then I'll post my solution which works on Django 2.0:
如果有人像我一样发现了这个问题,我将在Django 2.0上发布我的解决方案:
This tag assigns some settings.py variable value to template's variable:
这个标签分配一些设置。py变量值到模板变量:
Usage: {% get_settings_value template_var "SETTINGS_VAR" %}
用法:{% 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 == True %}
... 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/
参见Django的文档如何在这里创建自定义模板标签:https://docs.djangoproject.com/en/2.0/ howto/customtemplate-tags/。
#11
1
Adding an answer with complete instructions for creating a custom template tag that solves this, with Django 2.0
添加一个完整的说明来创建一个定制模板标签,它可以解决这个问题,Django 2.0。
In your app-folder, create a folder called templatetags. In it, create __init__.py and custom_tags.py:
在app-文件夹中,创建一个名为templatetags的文件夹。,创建__init__。py和custom_tags.py:
In the custom_tags.py create a custom tag function that provides access to an arbitrary key in the settings constant:
custom_tags。py创建一个自定义标记函数,在设置常量中提供对任意键的访问:
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.
为了理解这段代码,我建议您阅读Django文档中关于简单标记的部分。
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:
然后,您需要通过将该文件加载到将要使用它的任何模板中来让Django了解这个(以及任何其他)自定义标记。就像你需要加载内置的静态标签:
{% 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:
加载后,它可以像其他任何标记一样使用,只需提供需要返回的特定设置。因此,如果在设置中有一个BUILD_VERSION变量:
{% 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.
这个解决方案不能使用数组,但是如果需要的话,您可能需要在模板中加入很多逻辑。
#12
0
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.
IanSR和bchhun都建议在设置中重写template_context_processor。请注意,此设置有一个默认值,如果不重新设置默认值就重写它,可能会导致一些奇怪的事情。在Django的最新版本中,默认值也发生了变化。
https://docs.djangoproject.com/en/1.3/ref/settings/#template-context-processors
https://docs.djangoproject.com/en/1.3/ref/settings/ template-context-processors
The default 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")
#13
0
I found this to be the simplest approach for Django 1.3:
我发现这是Django 1.3最简单的方法:
-
views.py
views.py
from local_settings import BASE_URL def root(request): return render_to_response('hero.html', {'BASE_URL': BASE_URL})
-
hero.html
hero.html
var BASE_URL = '{{ JS_BASE_URL }}';
#14
0
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.
如果我们在单个变量上比较上下文和模板标记,那么知道更有效的选项是有益的。但是,最好只从需要该变量的模板中进行设置。在这种情况下,将变量传递给所有模板是没有意义的。但是如果您要将变量发送到一个通用模板(比如base)中。html模板,那么它作为基础就不重要了。每个请求都呈现html模板,因此您可以使用这两种方法。
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
示例:get_from_settings my_variable为my_context_value。
Example: get_from_settings my_variable my_default as my_context_value
示例:get_from_settings my_variable my_default为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)