Django:如何在模板中使用设置?

时间:2011-01-29 11:37:36

标签: python django django-templates

Django:如何在模板中使用设置?

4 个答案:

答案 0 :(得分:13)

您可以将设置传递给模板,如下所示:

from django.conf import settings
from django.template import RequestContext

def index(request):
        return render_to_response('index.html', {'settings': settings},
        context_instance=RequestContext(request))

在模板中:

{{ settings.MY_SETTING_NAME }}

如果您需要在许多模板(许多视图)中访问您的设置,请考虑创建适当的template context processor

答案 1 :(得分:2)

如果使用基于类的视图:

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

答案 2 :(得分:0)

只需导入它。

from django.conf import settings

答案 3 :(得分:0)

非常简单。

像这样:

from django.conf import settings

print settings.MY_SETTING_NAME