Wednesday, October 29, 2014

Re: What is the purpose of the include function?

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)

iQIcBAEBCAAGBQJUUV01AAoJEC0ft5FqUuEhaZAQAIU1fZab9ddV8B+WoFlB/SuS
djj7FglvKEkK56NWfZ534bBgseJ8gdsf02A6vZmkThrkqSw1B9IS/J22I3TX0XOy
bUc0H2PsMYjJgRvv69Wjp6qEIlLWHSckk+CfWyUfZv5kT66i0wplSIHNG4gzDVuG
+uA+1NgpDaJYH9ptrIUmc/NfelT6Y0uM6Ut7JuXIGddv9z7WhPfHnRCj18Adi6hQ
Sx8OGaE0rpVyGJx2R9+BnvOV6ZfuoqgPHO4ASqDqdKgCJMIgMkhTyo+nMIzSiKFn
NwdmNzIir0W7pe3qH3vPF5YTtIjtcoY31qBWONrENRN3rGi/OE424mTMfto5uf28
GRHfZznsNtyXVvJr62p5VCqzbcJ59dtPWW5V42jZW0JIjIZZdgUdE+g9hUjVK/si
XJHtdHyuwB9TvD710AOjVCYjhtsrPVeNbCNoPdfs2BJmKfmL6uopu4LAj4B9ztSw
k750jKglVRHHKpUjgQw6vv6TzvNepWKGTc3g8NAt7ko6zVlKBRBTKYkJmDNFUK2g
eQI1VRKQul+3X6ScOwfAgs2lNlQkIAF/9eSyFfC+YelCHMntCI0klZ7ssgsd0qK7
anKr9xC7ZCNpPBbw5ktcIXkNibW10HAVFxPmMq6Go0tzBSHRr1l3IFEc54GjwJBG
+uH2VV/zfnjcqAKtO9C9
=SirP
-----END PGP SIGNATURE-----
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

No comments:

Post a Comment