Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, name parameter in urlpatterns

I'm following a tutorial where my urlpatterns are:

urlpatterns = patterns('',     url(r'^passwords/$', PasswordListView.as_view(), name='passwords_api_root'),     url(r'^passwords/(?P<id>[0-9]+)$', PasswordInstanceView.as_view(), name='passwords_api_instance'),     ...other urls here..., ) 

The PasswordListView and PasswordInstanceView are supposed to be class based views. I could not figure out the meaning of the name parameter. Is it a default parameter passed to the view?

like image 555
Leonardo Avatar asked Oct 10 '12 11:10

Leonardo


People also ask

What is name in Urlpatterns in Django?

It is just that django gives you the option to name your views in case you need to refer to them from your code, or your templates. This is useful and good practice because you avoid hardcoding urls on your code or inside your templates.

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How do I get all query parameters in Django?

We can access the query params from the request in Django from the GET attribute of the request. To get the first or only value in a parameter simply use the get() method. To get the list of all values in a parameter use getlist() method.


1 Answers

No. It is just that django gives you the option to name your views in case you need to refer to them from your code, or your templates. This is useful and good practice because you avoid hardcoding urls on your code or inside your templates. Even if you change the actual url, you don't have to change anything else, since you will refer to them by name.

e.x with views:

from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse #this is deprecated in django 2.0+ from django.urls import reverse #use this for django 2.0+  def myview(request):     passwords_url = reverse('passwords_api_root')  # this returns the string `/passwords/`     return HttpResponseRedirect(passwords_url) 

More here.

e.x. in templates

<p>Please go <a href="{% url 'passwords_api_root' %}">here</a></p> 

More here.

like image 57
rantanplan Avatar answered Sep 24 '22 05:09

rantanplan