Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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".

like image 897
truease.com Avatar asked Sep 02 '25 05:09

truease.com


2 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.

like image 96
DrTyrsa Avatar answered Sep 04 '25 19:09

DrTyrsa


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 %}
like image 31
Santiago Alessandri Avatar answered Sep 04 '25 20:09

Santiago Alessandri