I am studying the Django documentation, but I encountered a part that I cannot understand: what is a real example of how use to use a namespace in a real problem. I know the syntax but I do not know the purpose of this.
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
- UnicodeEncodeError when saving ImageField containi
Typically, they are used to put each application's URLs into their own namespace. This prevents the
reverse()
Django function and the{% url %}
template function from returning the wrong URL because the URL-pattern name happened to match in another app.What I have in my project-level
urls.py
file is the following:Note the last section: this goes through the applications I have installed (
settings.LOCAL_APPS
is a setting I added that contains only my apps; it gets added toINSTALLED_APPS
which has other things like South), looks for aurls.py
in each of them, and imports those URLs into a namespace named after the app, and also puts those URLs into a URL subdirectory named after the app.So, for example, if I have an app named
hosts
, andhosts/urls.py
looks like:Now my
views.py
can callreverse("hosts:list")
to get the URL to the page that callshosts.views.show_hosts
, and it will look something like"/hosts/"
. Same goes for{% url "hosts:list" %}
in a template. This way I don't have to worry about colliding with a URL named "list" in another app, and I don't have to prefix every name withhosts_
.Note that the login page is at
{% url "login" %}
since it wasn't given a namespace.Consider you are using a url pattern as below
url(r'^login/',include('app_name', name='login'))
Also Consider you are using a third-party app like Django-RestFramework. When you use the app, you have to declare the following line in URLs conf file of the project.
Now if you check the code of rest-framework, you will find the below code in urls.py file
We have used 'login' name for a URL pattern in our project and the same name is being used by Django-rest-framework for one of their URL patterns. When you use reverse('login'), Django will get confused.
To resolve these kinds of issues, we use namespace.
URL names of a namespace will never collide with other namespaces.
A namespaced URL pattern can be reversed using
reverse('namespace:url_name')