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!
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 .
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).
{% 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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With