Django: what's the difference between import / use include () and not use when configuring a URL?

4
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

In this example I saw that there are two ways to call a URL, one with include() and the other with no include. What's the difference?

    
asked by anonymous 30.12.2015 / 16:51

1 answer

4

In a system, there may be hundreds of urls. It gets somewhat disorganized you put everything into just one url file. There is a main urls.py file that comes in the same settings directory. The include suggests that you are working with another url file that has that prefix in front.

As you create your apps, it's best to have a urls.py file for each app.

For example, assuming you create an app called Products:

In your main urls.py, you would have:

from django.conf.urls import include, url from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^produtos/', include('produtos.urls', namespace='produtos')),
]

Within the products app you can create a new urls.py file with all urls for that app:

# -*- coding: utf-8 -*-

from django.conf.urls import patterns, include, url

urlpatterns = patterns('produtos.views',
    url(r'^novo/$', 'produto_novo', name='produto'),
    url(r'^editar/(?P<pk>\d+)/$', 'editar_produto', name='editar'),
    url(r'^lista/$','lista_produtos', name='lista'),
)

These urls for this new file could be yes only in the main urls.py file, but this is not good practice. Which is simpler, look for a url in a file with 30 urls or in a file that has only 3 urls?

The namespace that I put in the main urls, serves for the url call, for example:

<a href="{% url 'produtos:novo' %}">Novo Produto</a>

If it's just an institutional site you're doing in django, it's fine to leave everything in the main urls, but for example, I work on systems that have more than 100 urls.

I hope I have helped.

    
02.01.2016 / 01:31