1

My Django skill level: noob.

I am going nuts at setting the DJANGO_SETTINGS_MODULE properly to finally get my model imported within a script. I use a virtualenv for my project.

This is my current error:

ModuleNotFoundError: No module named 'dashex'

And the according feeder.py script:

import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'dashex.settings'
sys.path.append('os.path.dirname(os.path.dirname(os.path.abspath(__file__)))')
import django
django.setup()
import zmq
import time
from time import sleep
import uuid
from Dashboard_app.models import AccountInformation
[...]

Background:

I first used the settings.configure() solution posted here. However, this solution raised this error... So I hope DJANGO_SETTINGS_MODULE can do the trick.

According to the documentation (docu) I have to use Django-admin to set DJANGO_SETTINGS_MODULE.

What I've tried:

  • Executed
    $ set DJANGO_SETTINGS_MODULE=dashex.settings in my command prompt on windows, just nothing happens.

  • Executed
    $ py manage.py set DJANGO_SETTINGS_MODULE=dashex.settings which raises the error unknown command set

  • Executed
    $ django-admin set DJANGO_SETTINGS_MODULE=dashex.settings in the manage.py root of my project raises the error no module named dashex.

  • This answer from @Casper suggests to do the above mentioned, but how to handle this:
    C:\temp\testproject> set DJANGO_SETTINGS_MODULE=testproject.settings ?

  • This solution from @Max suggests to append export DJANGO_SETTINGS_MODULE=<django_project>.settings to my virtual-environment. What is meant with this, how to do that?

  • Executed
    $ django-admin runserver --settings=dashex.settings which also raises the error no module named dashex.

  • Executed
    $ py manage.py runserver --settings=dashex.settings which starts the server with the proper settings. But the initial mentioned error persists.

enter image description here

My project:

enter image description here

Settings.py:

import os.path
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/


STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["127.0.0.1", "locahost"]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    #other Apps
    'Wiki_app',
    'rest_framework',
    'Dashboard_app.apps.DashboardAppConfig'
]

Latest traceback after @alasdair's solution:

Traceback (most recent call last):
  File "C:\Users\Jonas Blickle\Desktop\dashex\Dashboard_app\feeder.py", line 6, in <module>
    django.setup()
  File "C:\Program Files\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\Program Files\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
    self._setup(name)
  File "C:\Program Files\lib\site-packages\django\conf\__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Program Files\lib\site-packages\django\conf\__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Program Files\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'dashex'
[Finished in 0.37s]

Working solution:

import sys
sys.path.insert(0, r"C:\Users\Jonas\Desktop\Dashex")
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'Dashex.settings'
import django
django.setup()
from Dashboard.models import AccountInformation
[...]
JSRB
  • 2,492
  • 1
  • 17
  • 48
  • 1
    You don't need to do any of this. You should use manage.py instead of django-admin, which takes care of it for you. Although note you cannot avoid working with the shell at some point. – Daniel Roseman Dec 03 '19 at 15:14
  • @DanielRoseman added the results using `manage.py` above. I have the server running with the correct settings, but when I run the script I get the very same error again. – JSRB Dec 03 '19 at 15:20
  • Don't use imports like `from models import AccountInformation`. Always do your imports relative to the project directory (the one with `manage.py`). So that import should be `from Dashboard_app.models import AccountInformation`. – Alasdair Dec 03 '19 at 15:40
  • @Phanti when Daniel says "use manage.py instead", he's talking about [using custom management commands](https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/) that can be invoked using manage.py. This is the official canonical blessed way to run scripts on your Django project, and actually much simpler (and reliable) than messing with envvars etc. – bruno desthuilliers Dec 03 '19 at 16:08

1 Answers1

2

django-admin and manage.py are not used to set environment variables, so the commands in your question like django-admin set DJANGO_SETTINGS_MODULE=dashex.settings don't make sense.

On Windows, you can run set DJANGO_SETTINGS_MODULE=dashex.settings in the command prompt before running the script. You say you don't want to use the shell, so it might be easier to set the environment variable in the script instead.

import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'dashex.settings'

# Since feeder.py is in Dashboard_app, you need to add the parent directory
# to the python path so that dashex can be imported
# (without this you'll get the 'no module named dashex' error)
sys.path.append('..')

import django
django.setup()

# Now you can import models
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Thank you for your help. I edited my script accordingly and it now raises `no module named dashex`. :-( I added the traceback above. – JSRB Dec 03 '19 at 15:32
  • Do you have `dashex` in your `INSTALLED_APPS`, or something that does an import from `dashex` in one of your `INSTALLED_APPS`? – Alasdair Dec 03 '19 at 15:38
  • Besides my `wiki_app` which doesn't import anything from module `dashex` I don't have any further apps. `Dashex` itself isn't in my `INSTALLED_APPS` because it is the base project root which holds the `settings.py`. Also changing the import to relative keeps raising the error `no module named dashex`. – JSRB Dec 03 '19 at 15:41
  • Is there anything special I have to put into `sys.path.append('..')` for the two dots? – JSRB Dec 03 '19 at 16:05
  • No, I meant to `..` (which means the parent directory). Perhaps the current working directory isn't what I'm expecting. Instead of `..` try `os.path.dirname(os.path.dirname(os.path.abspath(__file__)))`. Try printing that value as well to make sure it's correct - it should give you the directory that contains `manage.py`. – Alasdair Dec 03 '19 at 16:12
  • I tried `sys.path.append('os.path.dirname(os.path.dirname(os.path.abspath(settings.py)))')` but doesn't work. I included the latest code for the script into the initial post. Ridiculous that it is so hard to run a small script in Django -.- – JSRB Dec 03 '19 at 16:18
  • You're using a hardcoded string `'os.path.dirname(...)'`. Change it to `sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(settings.py))))`. – Alasdair Dec 03 '19 at 21:35
  • Thank you again. After some more try and error I finnaly got it to work. I post the working solution to the initial post. – JSRB Dec 04 '19 at 08:43