Django: What’s the difference between importing/using include() and not using when configuring a URL?

Asked

Viewed 273 times

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 one without include. What’s the difference?

1 answer

4


In a system, there can be hundreds of urls. It gets a bit disorganized you put everything in just one url file. There is a main urls.py file that comes in the same directory as Settings. include suggests that you are working with another url file that has that prefix on the front.

As you create your apps, the appropriate thing is for you to have a.py urls file for each app.

For example, suppose you create an app called products:

On 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 the urls referring to 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 of this new file could be 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 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 that you’re doing in Django, it’s okay to leave everything in the main urls, but I for example, work on systems that have more than 100 urls.

I hope I’ve helped.

  • Man, very good! I understand perfectly now. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.