I was poking around my friends project and as I looked through the urls.py file i noticed this:
url(r'^apply/$', contact.as_view(), name='careers_contact'),
I just recently learned about class based views, and it all makes sense to me except for the last bit name='careers_contact'
. I also can't seem to find the meaning of this online.
Can someone shed light on what this is, where that name lives, and what its doing?
NAME OF URL means the name that we give the name to a URL inside name argument of path() that means we only have to use name of the URL inside href attribute, we now don't have to use the hectic and complex url everywhere inside our code that's awesome feature of Django.
URL namespaces allow you to uniquely reverse named URL patterns even if different applications use the same URL names. It's a good practice for third-party apps to always use namespaced URLs (as we did in the tutorial). Similarly, it also allows you to reverse URLs if multiple instances of an application are deployed.
What happens when url.py file is edited while the development server is still running? Development server terminates.
url()
name
parameter"What is it? Where does it live?"
url()
is simply a function that returns a django.core.urlresolvers.RegexURLPattern
object, so passing in a name='careers_contact'
argument sets name
for that object. None of that is really relevant until this url(...)
is placed into a URLconf.
THEN, if we need the URL of a view, we can now get it by passing that name
into {% url 'careers_contact' %}
in templates or reverse('careers_contact')
in code and on the backend those functions will use the name
to map back to the correct URL.
Why do we need it?
We can reverse the Python Path to get the URL (ex. reverse(blog.views.home)
), so what's the point in using name
?
(Click the links for an example of the issue and how naming/namespacing solves it)
The reason they probably added a namespace for the URL is so that they can do reverse namespaced URL.
For example in a template somewhere, you will probably see something like:
<a href="{% URL 'contact:careers_contact' %}"> Click me! </a>
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