How can I correctly set DJANGO_SETTINGS_MODULE for my Django project (I am using virtualenv)?

后端 未结 7 1650
误落风尘
误落风尘 2020-12-07 21:22

I am having some trouble setting the DJANGO_SETTINGS_MODULE for my Django project.

I have a directory at ~/dev/django-project. In this directory I have

相关标签:
7条回答
  • 2020-12-07 21:32

    Don't run django-admin.py for anything other than the initial project creation. For everything after that, use manage.py, which takes care of the finding the settings.

    0 讨论(0)
  • 2020-12-07 21:32

    My favourite alternative is passing settings file as runtime parameter to manage.py in a python package syntax, e.g:

    python manage.py runserver --settings folder.filename
    

    more info django docs

    0 讨论(0)
  • 2020-12-07 21:33

    Yet another way to do deal with this issue is to use the python dotenv package and include PYTHONPATH and DJANGO_SETTINGS_MODULE in the .env file along with your other environment variables. Then modify your manage.py and wsgi.py to load them as stated in the instructions.

    from dotenv import load_dotenv
    load_dotenv()
    
    0 讨论(0)
  • 2020-12-07 21:34

    On unix-like machine you can simply alias virtualenv like this and use alias instead of typing everytime:

    .bashrc

    alias cool='source /path_to_ve/bin/activate; export DJANGO_SETTINGS_MODULE=django_settings_folder.settings; cd path_to_django_project; export PYTHONPATH=$PYTHONPATH:$PWD'

    0 讨论(0)
  • 2020-12-07 21:38

    I know there are plenty answers, but this one worked for me just for the record.

    1. Navigate to your .virtual_env folder where all the virtual environments are.
    2. Go to the environment folder specific to your project
    3. Append export DJANGO_SETTINGS_MODULE=<django_project>.settings or export DJANGO_SETTINGS_MODULE=<django_project>.settings.local if you are using a separate settings file stored in a settings folder.
    0 讨论(0)
  • 2020-12-07 21:47

    I just encountered the same error, and eventually managed to work out what was going on (the big clue was (Is it on sys.path?) in the ImportError).

    You need add your project directory to PYTHONPATH — this is what the documentation means by

    Note that the settings module should be on the Python import search path.

    To do so, run

    $ export PYTHONPATH=$PYTHONPATH:$PWD
    

    from the ~/dev/django-project directory before you run django-admin.py.

    You can add this command (replacing $PWD with the actual path to your project, i.e. ~/dev/django-project) to your virtualenv's source script. If you choose to advance to virtualenvwrapper at some point (which is designed for this kind of situation), you can add the export PY... line to the auto-generated postactivate hook script.

    mkdjangovirtualenv automates this even further, adding the appropriate entry to the Python path for you, but I have not tested it myself.

    0 讨论(0)
提交回复
热议问题