简体   繁体   中英

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

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.

In myproject.settings make following changes :

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

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',
...

Try:

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

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.

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 ie myproject

Django project ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM