views:

159

answers:

2

How can I reverse a url but with a different template name? I specifically have to use urlresolvers.reverse

To be more specific:

I have one view but two urls from which it could be accessed

(r'^url/$', 'view1', {'template1':'template1.html'}, 'access-url1'),
(r'^url_dynamic/$', 'view1', {'template1':'template_dynamic.html'}, 'url-dynamic'),

I don't want to write any code differentiating what template to return in the view because I might want change it on the fly. So I need the flexibility to change the url while calling it for eg

urlresolvers.reverse('view1', kwargs = {'template1':'template_dynamic.html'})
(which btw does not work throws noreversematch)

I could also just copy view1 into view2 and call it with url-dynamic but that would violate DRY.

A: 

If you really must use reverse to accomplish this, you could do something sneaky with your kwargs to pass it the template name.

The function signature for reverse() looks like this:

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)

You would need your view function to accept a template name/string as an (optional) argument. Then you'd just

{% url my.view.function "this_is_a_template.html" %}
Gabriel Hurley
I tried that with the template name as a part of kwargs but i got a NoReverseMatch
crashekar
you can't use reverse to pass anything that's not a part of the urlconf that leads to your function to begin with. You'll have to modify both your view function and urlconf to make this work.
Gabriel Hurley
+2  A: 

urlresolvers.reverse reverses kwargs that match those in the regex pattern, not the kwargs passed via the dict, in the url.

You might want to use the reverse('url-name') variant instead.

For your case it is going to be:

urlresolvers.reverse('url-dynamic')
Lakshman Prasad
This works fine. I was obsessing about adding the view name while reversing.
crashekar