Q: Django ImproperlyConfigured - from django.contrib.auth.models import User

I have a Django project called Veganet that I am trying to run, but when I run my main script vega_flask_run.py it gives me an improperly configured error. The source of the error is coming from a script named models.py, more specifically line 2 where I am declaring from django.contrib.auth.models import User. I have tried to use a few posts to solve my problem including:

I have tried solutions like changing the INSTALLED_APPS variable in my projects settings.py and changing the DATABASES variable inside settings.py, as well as using Windows Powershell to execute python manage.py shell, django-admin.py shell --settings=mysite.settings, and then setting the DJANGO_SETTINGS_MODULE variable to point to my projects settings and lastly using

from django.core.management import setup_environ
from veganet import settings

setup_environ(settings)

here is the error in it's entirety:

Exception has occurred: ImproperlyConfigured
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
  File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\models.py", line 2, in <module>
    from django.contrib.auth.models import User
  File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\forms.py", line 2, in <module>
    from .models import ExperimentContext, Profile
  File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_ai\VegaMain.py", line 25, in <module>
    from profiles.forms import ProfileModelForm, ExperimentModelForm
  File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_flask_run.py", line 5, in <module>
    from vega_ai.VegaMain import app as frontend

Here is my simplified file structure:

veganet (main folder)
 -profiles (folder)
  ...
  models.py (script that gives me the error)
  signals.py
  urls.py
  utils.py
  views.py
 -vega_ai (folder)
  VegaMain.py 
  ...
 -vega_net (folder)
  ...
  asgi.py
  settings.py
  urls.py
  views.py
  wsgi.py
 db.sqlite3
 manage.py 
 vega_flask_run.py (where I am running the project)

my settings.py file:

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-p8!i$5eqn)l(f0(n##1yntb^#ctfm3u*)j9xrjy^(1n9s&jdsa'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'posts',
    'profiles',
    'veganet',
]

LOGIN_URL = '/admin/'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'veganet.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["C:/Users/trevo/OneDrive/Desktop/veganet/templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'veganet.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

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

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")

MEDIA_URL = '/media/'
MEDIA_ROOT = 'C:/Users/trevo/OneDrive/Desktop/veganet/static_cdn/media_root'

my wsgi.py script:

import os
from django.conf import settings
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'veganet.settings')

application = get_wsgi_application()

models.py

from django.db import models
from django.contrib.auth.models import User
from django.dispatch.dispatcher import receiver
from .utils import get_random_code
from django.template.defaultfilters import slugify
import subprocess

...

vega_flask_run.py

from email.mime import application
from flask import Flask, render_template
from werkzeug.serving import run_simple
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from vega_ai.VegaMain import app as frontend
from manage import app as backend
from werkzeug.exceptions import NotFound
app = Flask(__name__, template_folder="C:/Users/trevo/OneDrive/Desktop/veganet/profiles/templates/profiles", static_folder="C:/Users/trevo/OneDrive/Desktop/veganet/static_project")


app.wsgi_app = DispatcherMiddleware(frontend, {
    '/app2':app,
    '/app3':backend
})

if __name__ == '__main__':
    app.run(debug=True,port=8080,use_reloader=False)

What exactly am I missing here? Thank you


Solution 1:

If this is Django, and not flask as the vega_flask_run.py name implies then you need to run python manage.py runserver to start the application.

This might be a duplicate of Django ImproperlyConfigured for import User.

Also, models.py is not a script your run in django in the manner I think you're saying. It is where the models you define, the classes, for your project are located.

I may be the one missing something. Maybe you can edit your question with the vega_flask_run.py file. Perhaps you're using it in a way that I'm just not familiar with.

Otherwise, I suggest you start with https://docs.djangoproject.com/en/4.0/intro/tutorial01/. I mean it looks like you've already started the project correctly since you have the django files there. Maybe it's just a matter of how you start them.

Edit
Yes, now I can see that you're trying to run a djagno app as if it were a flask app, app = Flask(__name__, .... Despite both Flask and Django being python frameworks, they are run very differently.