Search code examples
pythondjangourldispatcher

Getting current url


I have a couple of views which are rendering the same template and I have some {% url %} tags into that template which needs to point to different location based on the current view. Is there any context variable which gives the name of the view(for named urls), like view-1 view-2, so in my template I can use it like this:

{% url url-name %}

It is also possible to pass additional information to the template so I can understand which view is called. But that would not be an elegant solution I guess.


Solution

  • It is also possible to pass additional information to the template so I can understand which view is called. But that would not be an elegant solution I guess.

    Sure it is. Here's an example:

    def view1(request, form_class=MyForm, template_name='myapp/page.html'):
        # app code here
        this_url = reverse('view1')
        render_to_response(template_name, locals(), RequestContext(request))
    
    def view2(request, form_class=MyForm, template_name='myapp/page.html'):
        # app code here
        this_url = reverse('view2')
        render_to_response(template_name, locals(), RequestContext(request))
    

    myapp/page.html:

    <a href="{{ this_url }}">Webpage</a>
    

    You can also create your own url tag called, say, dynurl that takes the first argument as a variable instead of as the view name:

    def view2(request, form_class=MyForm, template_name='myapp/page2.html'):
        # app code here
        this_view = 'view2'
        render_to_response(template_name, locals(), RequestContext(request))
    

    myapp/page.html:

    {% load dynurl_tags %}
    <a href="{% dynurl this_view %}">Webpage</a>
    

    You haven't exactly explained why you want a link to the current view, though. Is it in order to link to the same page? There are a couple of ways to do that:

    <a href="">technically this points back to the same page</a>
    <a href="{{ request.path }}">this url is the full path before the query string</a>
    <a href="{{ request.get_full_path }}">this url is the full path plus the query string</a>
    

    I think it would be useful to think about what the key differences are between the two views and come up with a variable that describes their difference. Then use that variable in the template to determine the new URLs.

    For more complex problems you might want to look at Pinax groups and how they implement a {% groupurl %} tag. Basically it lets you duplicate all the urls of a given app and pass in a "group" variable that's used to create a special group-based reverse lookup for urls.