Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django urls.py, what does the name parameter do?

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?

like image 845
ApathyBear Avatar asked May 07 '14 19:05

ApathyBear


People also ask

What is name in URL path Django?

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.

Why do we name space URL names using the App_name variable in the urls py file?

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 urls py is edited?

What happens when url.py file is edited while the development server is still running? Development server terminates.


2 Answers

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?

URL Naming and Namespacing allow for 3 things:

  • A simple way to reverse URL match Class-Based Views. Though it is possible without it.
  • A way to distinguish URL patterns using the same view and parameters.
  • A way to differentiate URL names between apps.

(Click the links for an example of the issue and how naming/namespacing solves it)

like image 144
pcoronel Avatar answered Oct 04 '22 21:10

pcoronel


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>
like image 31
Alf Avatar answered Oct 04 '22 22:10

Alf