简体   繁体   中英

Default/logical directory structure for Django

I have gone through a number of tutorials, built a few apps, and even read the book by one of the creators of Django. But I am mystified by the 'proper' directory structure.

One always seems to get a tree that looks like this (with a virtual environment at the top):

venvdir
   |
   +---manage.py 
   |
   +---mysitedir 
   |       +--settings.py
   |       +--urls.p
   |       +--staticfiles (where collectstatic puts everything)
   |
   +---myapp1dir
   |       +--views.py
   |       +--models.py
   |       +--staticdir
   |             +---static-objects-tree...

What I find confusing is that

 os.path.abspath(__file__) 

points to 'mysitedir' (the references say it always points to the dir with settings.py in it).

Presumably the idea is that a whole 'site' has one or more 'apps' under it, though I have never seen that done as such.

First, is that correct?

Second, is there some compelling reason (or am I doing it wrong) such that the 'apps' don't slot in below 'mysitedir'? That would seem to make more sense and maintain modularity.

It seems odd the way Django does things like going through the whole tree looking for static files. It also seems illogical that you list the 'apps' in settings.py, and - once again - Django needs to go traversing up and back down to find these files (instead of just being able to look in the directory specified by os.path.abspath( file ).

Note that the default project layout is just a suggestion, there's nothing stopping you putting your apps in the mysitedir if you wish.

Django wants it to be easy to make re-usable apps. When you run manage.py runserver , the directory containing manage.py is on the Python path. Therefore you can import apps in that directory with myapp1 , myapp2 etc.

If you moved the apps to the inner mysitedir (the one that contains settings), then you would import the apps with mysitedir.myapp1 , mysitedir.myapp2 etc. Your code now has the project name hardcoded, so it is less reusable.

Finally, Django doesn't really go "traversing up and down" the directories of the project. When you do import myapp , Python imports the module from the Python path. This could be the outer project directory that contains manage.py , or if it's an installed package, it could be somewhere completely different.

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