How to get django view function url

eg:

view.py

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

urls.py

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

where should i get the url to view1 how do i do this? Of course, I don’t want to hardcode the URL "xxx / view1".

+6
source share
6 answers

You need reverse .

 reverse('app1.view.view1') 

If you want to know the url and redirect it, use redirect

 redirect('app1.view.view1') 

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

+15
source

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

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

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

 {% url 'path.to.some_view' v1 v2 %} 
+8
source

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

I would recommend adding a name to your URL pattern.

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

and cancel it thanks to this name

 reverse('view1') 

This will make your code easier to refactor.

+3
source

If you need the URL of view1 in view1, the best thing is request.get_path ()

+2
source

Yes, of course, you can get the view URL with the name "view1" without hard-coding the URL.

All you have to do is just import the "reverse" function from Django urlresolvers.

Have a look at the below code example:

 from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect def some_redirect_fun(request): return HttpResponseRedirect(reverse('view-name')) 
+2
source

You can use the reverse function for this. You could specify namespaces and names for url-include and urls respectively to simplify refactoring.

+1
source

Source: https://habr.com/ru/post/915391/


All Articles