在模板中使用Django设置

Rog*_*ger 23 python django django-templates

我希望能够将某些配置信息放在我的settings.py文件中 - 例如站点名称,站点URL等.

如果我这样做,我怎么才能在模板中访问这些设置?

谢谢

Ger*_*alt 44

让我们在您的settings.py文件中说:

SITE_URL='www.mydomain.tld/somewhere/'
SITE_NAME='My site'
Run Code Online (Sandbox Code Playgroud)

如果只需要一两个视图就需要它:

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

def my_view(request, ...):
    response_dict = {
        'site_name': settings.SITE_NAME,
        'site_url': settings.SITE_URL,
    }
    ...
    return render_to_response('my_template_dir/my_template.html', response_dict)
Run Code Online (Sandbox Code Playgroud)

如果您需要跨很多应用程序和/或视图访问这些应用程序和/或视图,您可以编写上下文处理器来保存代码:

詹姆斯有一个在线教程 .

关于何时以及是否context处理器可以用这个非常站点的一些有用的信息 在这里.

在您的my_context_processors.py文件中,您将:

from django.conf import settings

def some_context_processor(request):
    my_dict = {
        'site_url': settings.SITE_URL,
        'site_name': settings.SITE_NAME,
    }

    return my_dict
Run Code Online (Sandbox Code Playgroud)

回到你的settings.py身边,通过这样做来激活它:

TEMPLATE_CONTEXT_PROCESSORS = (
    ...

    # yours
    'my_context_processors.some_context_processor',
)
Run Code Online (Sandbox Code Playgroud)

在您views.py的视图中使用它,如下所示:

from django.shortcuts import render_to_response
from django.template import RequestContext

def my_view(request, ...):  
    response_dict = RequestContext(request)
    ...
    # you can still still add variables that specific only to this view
    response_dict['some_var_only_in_this_view'] = 42
    ...
    return render_to_response('my_template_dir/my_template.html', response_dict)
Run Code Online (Sandbox Code Playgroud)


Bil*_*zke 5

如果使用基于类的视图:

#
# 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 }}
Run Code Online (Sandbox Code Playgroud)