'Django - include app urls

I have the following structure (Django 1.4):

containing_dir/
    myproject/
        myapp1/
        myapp2/
        myapp3/

myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.

In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

in myproject.settings i define:

[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (   
    [..]
    'myproject.myapp1',
    'myproject.myapp2',
    'myproject.myapp3',
)
[..]

In myapp1.urls.py I define:

urlpatterns = patterns('myapp1',
    url(r'^agent/$', 'views.agent',    name='agent')
)

and I try to import it in myproject.urls I try to import myapp1 urls like this:

(r'^myapp1/', include('myproject.myapp1.urls'))

but whenever I try lo load localhost:8000/myapp1/agent I get

Exception Value: No module named myapp1

I think thrown from withing myapp1.urls

Any help? thanks



Solution 1:[1]

You must have a

__init__.py

file inside your "myproject" directory. When you say:

(r'^myapp1/', include('myproject.myapp1.urls'))

you are saying "myproject" (as well as myapp1) is a python packege.

Solution 2:[2]

In myproject.settings make following changes :

INSTALLED_APPS = (   
[..]
'myapp1',
'myapp2',
'myapp3',
)

Solution 3:[3]

Try:

urlpatterns = [
    ...
    url(r'^app_name/', include('app_name.urls', namespace='project_name'))
    ...
]

Solution 4:[4]

Does ROOT_URLCONF need to point to myproject.urls?

If you place your apps inside of myproject you need to use the proper view prefix.

urlpatterns = patterns('myproject.myapp1',
...

Solution 5:[5]

To solve this issue just select "myproject" directory in PyCharm and set this as a source root. Your project don't know from which root it has to search for given app. It fixed the issue for me. Thank you.

Solution 6:[6]

Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.

You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject

Django project i.e. myproject urls.py file must be updated to include examples like:

path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))

Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.

Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.

ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]

For more information look at documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Vaishnav Mhetre
Solution 4 Ngenator
Solution 5 Codex
Solution 6 Shubhank Gupta