Answers
假如,你的settings.py有如下配置:
SITE_URL='www.mydomain.tld/somewhere/'
SITE_NAME='My site'
如果你只在少量的views中需要使用她们:
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)
如果你需要在很多apps / views使用这些配置,那么你需要写一个context processor,这样的好处是,可以复用代码:
具体可以参考 这个英文文档
你可以这样编写自己的mycontextprocessors.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
打开settings.py文件, 通过如下方式激活你的context_processor:
TEMPLATE_CONTEXT_PROCESSORS = (
...
# yours
'my_context_processors.some_context_processor',
)
打开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)
青春期骨痛
answered 10 years, 4 months ago