当我渲染模板时,我想通过给出命名空间值而不是路径来检索模板的URL。例如,而不是:
return render(request, 'base/index.html', {'user':name})
我希望能够做到以下几点:
from django.shortcuts import render
from django.core.urlresolvers import reverse
return render(request, reverse('base:index'), {'user':name})
但上面会产生错误。我该怎么做?有没有办法将命名空间赋予函数并获取实际路径?
扩展示例:
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('base.urls', namespace='base')),
)
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index', name='index'),
)
from django.shortcuts import render
from django.core.urlresolvers import reverse
def homepage(request):
'''
Here instead of 'base_templates/index.html' i would like to pass
something that can give me the same path but by giving the namespace
'''
return render(request, 'base_templates/index.html', {'username':'a_name'})
提前致谢。
答案 0 :(得分:0)
模板名称在视图中是硬编码的。您还可以做的是,您可以从网址格式传递模板名称,有关详细信息,请参阅here:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index',
{'template_name': 'base_templates/index.html'},
name='index'),
)
然后在视图中获取模板名称:
def index(request, **kwargs):
template_name = kwargs['template_name']