Django - include app urls

孤街浪徒 提交于 2020-06-10 08:46:31

问题


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


回答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.




回答2:


In myproject.settings make following changes :

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



回答3:


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



回答4:


Try:

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



回答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.



来源:https://stackoverflow.com/questions/15885030/django-include-app-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!