我可以从 Django 中的模板访问 settings.py 中的常量吗? [英] Can I access constants in settings.py from templates in Django?

查看:24
本文介绍了我可以从 Django 中的模板访问 settings.py 中的常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从模板访问 settings.py 中的一些内容,但我不知道该怎么做.我已经试过了

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?

推荐答案

Django 提供对模板的某些常用设置常量的访问,例如 settings.MEDIA_URL 和一些语言设置,如果您使用 django 内置的通用视图或在 render_to_response 快捷函数中传入上下文实例关键字参数.以下是每种情况的示例:

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

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

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)

现在您可以在模板上以 {{ favorite_color }} 的形式访问 settings.FAVORITE_COLOR.

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

这篇关于我可以从 Django 中的模板访问 settings.py 中的常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆