How do you set the python path for django-admin?

278 views
Skip to first unread message

Tobias Bengfort

unread,
Nov 8, 2023, 2:18:42 PM11/8/23
to django-d...@googlegroups.com
Hi everyone,

https://docs.djangoproject.com/en/4.2/ref/django-admin/ claims that
manage.py, django-admin and python -m django are practically
interchangable. However, I noticed that they behave differently when it
comes to the python path (the path you can import modules from). I used
`CMD shell -c 'import sys; print(sys.path[0])' to check each one:

- `manage.py` adds its own location to the python path. That is fine
because `django-admin startproject` puts it right next to the project
directory.

- `django-admin` also adds its own location to the python path. That is
less fine because that is usualy something like /some/venv/bin/, so the
project package is not importable. Simply running `django-admin
runserver --settings=example.settings` fails with `ModuleNotFoundError:
No module named 'example'`.

- `python -m django` uses the current directory, which is slightly less
useful than manage.py, but quite intuitive.

Of course you can circumvent all of this by setting PYTHONPATH explicitly.

I personally was burned by this because I use `pip install -e` to add
the folder containing the project directory to the python path. However,
when switching to PEP 517 based packaging, the behavior changed and some
modules could no longer be imported.

is there any official recommendation about this? My impression was
always that manage.py is meant for development and django-admin is meant
for production. But how are you supposed to set the python path in that
case? Is this assumption even correct? I could not find anything about
it in the docs.

In any case, I think the docs need an update because currently, all
examples use `django-admin`, which does not work out of the box in my
experience.

thanks,
tobias

Carlton Gibson

unread,
Nov 9, 2023, 4:14:34 AM11/9/23
to django-d...@googlegroups.com
Hi tobias. 

The django-admin command has a `--pythonpath` option for this (docs). 

So, for example in a 3rd party package using the src layout (example) where the module itself is installed in the venv, but the tests module is at the package root, you can run the tests like: 

    django-admin test --settings=tests.settings --pythonpath=.

HTH. 

Kind Regards,

Carlton

--
You received this message because you are subscribed to the Google Groups "Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/2b27a633-f658-4fe8-ab41-d553890b03c6%40posteo.de.
Reply all
Reply to author
Forward
0 new messages