0

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.

CodeArtist
  • 5,534
  • 8
  • 40
  • 65
  • 3
    `base/index.html` is the template name. `reverse` is used for reverse resolution of url names. Your logic is wrong. You cannot user `reverse` here. – Aamir Rind Mar 27 '13 at 14:10

1 Answers1

0

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']
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164