Reputation: 9605
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?
Upvotes: 5
Views: 3194
Reputation: 3981
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)
Upvotes: 11
Reputation: 852
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>
Upvotes: 3