What is the purpose of the include function?

39 views
Skip to first unread message

Daniel Grace

unread,
Oct 28, 2014, 5:51:48 PM10/28/14
to django...@googlegroups.com
Hi,
In reference to urls.py what is the purpose of the include function?  For example what is the difference between these two lines?
url(r'^admin/', admin.site.urls),
url(r'^admin/', include(admin.site.urls)),


Ben Lopatin

unread,
Oct 29, 2014, 9:41:38 AM10/29/14
to django...@googlegroups.com
Hi Daniel, in this case I would think the latter would fail - the `include` function loads a URL conf module and then finds the `urlpatterns` attribute, whereas `admin.site.urls` is a class method that dynamically builds a list of URL patterns based on your installed apps. There's nothing to import in the latter case because there's no such `urls` module.

Carl Meyer

unread,
Oct 29, 2014, 5:34:14 PM10/29/14
to django...@googlegroups.com
Hi Ben & Daniel,

On 10/29/2014 07:41 AM, Ben Lopatin wrote:
> Hi Daniel, in this case I would think the latter would fail - the
> `include` function loads a URL conf module and then finds the
> `urlpatterns` attribute, whereas `admin.site.urls` is a class method
> that dynamically builds a list of URL patterns based on your installed
> apps. There's nothing to import in the latter case because there's no
> such `urls` module.

`include()` can take a list of url patterns directly, too -- it doesn't
have to take a urlconf module with a `urlpatterns` attribute. In fact,
you can use ``include()`` entirely within one module, to include one set
of url patterns within another and reduce prefix repetition:

profile_patterns = [
url(r'^$', views.profile),
url(r'^edit/$', views.edit_profile),
]

urlpatterns = [
url(r'^$', views.home),
url(r'^(?P<user_id>\d+)/', include(profile_patterns)),
]

> On Tuesday, October 28, 2014 5:51:48 PM UTC-4, Daniel Grace wrote:
>
> Hi,
> In reference to urls.py what is the purpose of the include function?
> For example what is the difference between these two lines?
> url(r'^admin/', admin.site.urls),
> url(r'^admin/', include(admin.site.urls)),

I think in part through historical accident, both ``include()`` and
``url()`` can actually take a triple of (urlpatterns, app_name,
namespace), which is what `admin.site.urls` actually is. So in this
particular case there is in fact no difference.

But this is an odd case. In the more typical cases, you'd pass
`include()` either a string dotted path to a Python module with a
`urlpatterns` attribute which is a list of url patterns, or an actual
Python module object with a `urlpatterns` attribute which is a list of
url patterns, or simply a list of urlpatterns. And in almost every case,
you'd pass `url()` a view callable.

Carl

signature.asc
Reply all
Reply to author
Forward
0 new messages