Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "name" mean in Django-url? [duplicate]

Tags:

python

django

I was wondering, when using the url (from django.conf.urls import url), what does name = 'insert-something' mean? For example, when making a url for registering a new user:

url(r'^register', views.register, name='register')

What does name='register' mean here? Why is it necessary?

Thank you!

like image 261
Nora Avatar asked Oct 13 '17 12:10

Nora


People also ask

What does name do in Django urls?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

What happens when a URL is matched Django?

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).

What does form {% url %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

What is a URL pattern Django?

In Django, views are Python functions which take a URL request as parameter and return an HTTP response or throw an exception like 404. Each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration) Let the project name be myProject.


1 Answers

The name is used for accessingg that url from your Django / Python code. For example you have this in urls.py

url(r'^main/', views.main, name='main')

Now everytime you want to redirect to main page, you can say

redirect('app.main')

where app is the name of the django-app in which main is located. Or you can even use it for links in your html templates like

<a href="{% url 'app.main' %}">Go to main</a>

and this would link you to www.example.com/main for example. You could of course do

redirect('http://www.example.com/main')

or

<a href="http://www.example.com/main">Go to main</a>

respectively, but for example you want to change either domain or main/ route. If all urls would be hardcoded in your project, then you would have to change it in every place. But if you used url name attribute instead, you can just change the url pattern in your urls.py.

like image 141
campovski Avatar answered Nov 14 '22 09:11

campovski