[Django]-"Include" works weirdly

2👍

include works by including other django module’s urls and use current definition as root below other ones.

Django doc has very comprehensive explanation about this, I’m going to quote them here:

from django.conf.urls import include, url

from apps.main import views as main_views
from credit import views as credit_views

extra_patterns = [
    url(r'^reports/$', credit_views.report),
    url(r'^reports/(?P<id>[0-9]+)/$', credit_views.report),
    url(r'^charge/$', credit_views.charge),
]

urlpatterns = [
    url(r'^$', main_views.homepage),
    url(r'^help/', include('apps.help.urls')),
    url(r'^credit/', include(extra_patterns)),
]

Here the include(extra_patterns) would use credit/ as the root url and recognize any other urls defined in extra_patterns as an extension of the url definition to match urls. This avoids duplicate definitions like credit/reports, credit/charge, etc.

Same thing for include('apps.help.urls'), it would include all urls defined in module apps.help.urls with base url as help/. So you don’t have to define all urls in one place.

5👍

You appear to be including a view rather than a urls module

url(r'^home$', include(acc_views.home), name='accounts_home'),

should be

 url(r'^account/', include(account.urls, namespace='accounts'),

Include is designed to make it easy to link the patterns between different urls.py files, not to include a separate view, to do that you can just reference the view directly in a url as you would do normally.

What is include actually doing?

You can view the source code here

It essentially looks for patterns defined inside a urlpatterns variable.

👤Sayse

0👍

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x035424F8>
Traceback (most recent call last):
  File "C:\Python35-32\VirtualENV\socialnetwork296\lib\site-packages\django\core\urlresolvers.py", line 419, in url_patterns
    iter(patterns)
TypeError: 'function' object is not iterable

That tells you everything you should need to know. A function is not iterable. If you read the docs you’ll see that you can use any of these:

include(module, namespace=None, app_name=None)[source]
include(pattern_list)
include((pattern_list, app_namespace), namespace=None)
include((pattern_list, app_namespace, instance_namespace))

You’re passing it a function, I would guess, with acc_views.home. You probably want 'acc_views.home' the string or something to that effect, not the actual module.

Leave a comment