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

24👍

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.

Leave a comment