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

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

urlpatterns = [
    url(r'^polls/', include('polls.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


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 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 file for each app.

For example, assuming you create an app called Products:

In your main, you would have:

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

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

Within the products app you can create a new 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 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