How to get the url path of a view function in django

Question:

As an example:

view.py

def view1( request ):
    return HttpResponse( "just a test..." )

urls.py

urlpatterns = patterns('',
    url( r'^view1$', 'app1.view.view1'),
)

I want to get the URL path of view1. How can I do this.
I want to avoid hard coding any URL paths, such as “xxx/view1”.

Asked By: truease.com

||

Answers:

You need reverse.

from django.urls import reverse

reverse('app1.view.view1')

If you want to find out URL and redirect to it, use redirect

from django.urls import redirect 

redirect('app1.view.view1')

If want to go further and not to hardcode your view names either, you can name your URL patterns and use these names instead.

Answered By: DrTyrsa

You can use the reverse function for this. You could specify namespaces and names for url-includes and urls respectively, to make refactoring easier.

Answered By: DJ_HOEK

This depends whether you want to get it, if you want to get the url in a view(python code) you can use the reverse function(documentation):

reverse('admin:app_list', kwargs={'app_label': 'auth'})

And if want to use it in a template then you can use the url tag (documentation):

{% url 'path.to.some_view' v1 v2 %}
Answered By: Santiago Alessandri

If you want the url of the view1 into the view1 the best is request.get_path()

Answered By: Goin

As said by others, reverse function and url templatetags can (should) be used for this.

I would recommend to add a name to your url pattern

urlpatterns = patterns('',
    url( r'^view1$', 'app1.view.view1', name='view1'),
)

and to reverse it thanks to this name

reverse('view1')

That would make your code easier to refactor

Answered By: luc

Yes, of course you can get the url path of view named ‘view1’ without hard-coding the url.

All you need to do is – just import the ‘reverse’ function from Django urlresolvers.

Just look at the below example code:

from django.core.urlresolvers import reverse

from django.http import HttpResponseRedirect

def some_redirect_fun(request):

    return HttpResponseRedirect(reverse('view-name'))
Answered By: Shirisha

Universal approach

  1. install Django extensions and add it to INSTALLED_APPS

  2. Generate a text file with all URLs with corresponding view functions

./manage.py show_urls --format pretty-json --settings=<path-to-settings> > urls.txt

like

./manage.py show_urls --format pretty-json --settings=settings2.testing > urls.txt

  1. Look for your URL in the output file urls.txt
    {
        "url": "/v3/blockdocuments/<pk>/",
        "module": "api.views.ganeditor.BlockDocumentViewSet",
        "name": "block-documents-detail",
    },
Answered By: pymen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.