在渲染模板时,我想通过提供命名空间值而不是路径来检索模板的 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})
但上面会产生错误。我该怎么做?有没有办法将命名空间赋予函数并获取实际路径?
扩展示例:
- urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('base.urls', namespace='base')),
)
- 应用程序库:urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index', name='index'),
)
- 应用程序库:views.py
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'})
提前致谢。