12

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!

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
Nora
  • 1,825
  • 8
  • 31
  • 47
  • you can use that name with `reverse` [LINK](https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#reverse) – Alex Pshenko Oct 13 '17 at 12:24
  • 2
    Your url address may change anytime, so instead of writing hard code url in template tag, you can simply write: {`% url 'register' %}` – Natiq Vahabov Oct 13 '17 at 12:28

1 Answers1

22

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.

campovski
  • 2,979
  • 19
  • 38