Search code examples
djangodjango-templatesrenderreversedjango-context

Django: How can i get the url of a template by giving the namespace?


While i'm rendering a template i would like to retrieve the url of the template by giving the namespace value and not the path. For example instead of this:

return render(request, 'base/index.html', {'user':name})

i would like to be able to do the following:

from django.shortcuts import render
from django.core.urlresolvers import reverse

return render(request, reverse('base:index'), {'user':name})

but the above produces an error. How can i do it? Is there any way to give the namespace to a function and get the actual path?

Extended example:

- urls.py

from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('',
    url(r'^', include('base.urls', namespace='base')),
)

- app base: urls.py

from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('base.views',
   url(r'^/?$', 'index', name='index'),
)

- app base: 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'})

Thanks in advance.


Solution

  • Template names are hard coded within the view. What you can also do is that you can pass the template name from the url pattern, for more details see here:

    from django.conf.urls.defaults import patterns, url
    
        urlpatterns = patterns('base.views',
           url(r'^/?$', 'index',
              {'template_name': 'base_templates/index.html'},
              name='index'),
           )
    

    Then in view get the template name:

    def index(request, **kwargs):
        template_name = kwargs['template_name']