18👍
We usually set our projects up like this:
/site/
__init__.py
manage.py
settings.py
urls.py
/apps/
__init__.py
/appA/
__init__.py
/appB/
__init__.py
/lib/
__init__.py
/django-lib/
__init__.py
/shared-lib/
__init__.py
Just make sure your site directory is on your python path:
import sys
sys.path.append('/path/to/site/')
Also, ensure that an init.py exists in site, apps, and lib so they can be treated as modules using dot notation imports (import site.lib.shared-lib)
Edit:
In answer to your question regarding your python path, it all has to do with where your ‘manage.py’ or equivalent file resides. If it is under the /site/ directory (next to apps and lib) then the PYTHONPATH should be fine.
You need to make sure that every directory contains an empty file called __init__.py
. This tells Python to treat that directory as a module. See the new and improved ASCII art above.
14👍
What I learned from Two Scoops of Django is that you put the shared code inside a Django app that you create on your own called core
.
To use the core
app then is similar to how you cross-use classes from other apps.
To learn more, go to Chapter 28 of the book titled: “What About Those Random Utilities?”
- Django + uWSGI + Nginx + SSL – request for working configuration (emphasis on SSL)
- What does deconstructible do in Python?
1👍
If the shared library is going to be used in others projects as well you can make a installer using distutils.
But if it’s only for the apps in the project you can take AntonioP’s answer.
Remember that the root of your project (folder that contains manage.py) is always in your PYTHON_PATH when you run your django project, so you can create a folder deps
or dependencies
or extra
or anything you like it that contains your shared libraries.
- Django template indentation guideline
- How should I be implementing user SSO with AAD in a Django application (using the Django Microsoft Authentication Backend module)?
- Python: Can dumpdata cannot loaddata back. UnicodeDecodeError
- Django breaking long lookup names on queries