0

Not sure why I am getting this error when I try to call a function within my load_data()

django.core.exceptions.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.

However, when I run the crud_ops.py function it works fine and sets the records within the database

load_data.py

def publisher_data(listt, start):
    from reviews.models import Publisher
    check_list = []
    query_list = []

    for i in range(start + 1, len(listt)):
        if listt[i].__contains__("publisher"):
            check_list.append(listt[i])
        else:
            query_list.append(listt[i])

        if len(query_list) == len(check_list):
            print(query_list)
            publisher = Publisher(name=query_list[0], website=query_list[1],
                                  email=query_list[2])
            publisher.save()

            query_list = []
        if listt[i].__contains__("content"):
            break

def load_data():

   file_read = open("WebDevWithDjangoData.csv", "r")
   text = file_read.read().split(",")
   new_list = [x for x in text if x.strip() != '']
   list_1 = []
   start_index = None
   end_index = None
   for x in new_list:
       list_1.append(x.strip())
   file_read.close()


  for x in range(len(list_1)):
       #print(list_1[x])
       if list_1[x] == "content:Publisher":
          start_index = x
          publisher_data(list_1, start_index)

crud_ops.py:

def crud_ops():
    from reviews.models import Publisher, Contributor
    publisher = Publisher(name='Packt Publishing', website='https://www.packtpub.com', email='info@packtpub.com')
    publisher.save()
    publisher.email = 'customersupport@packtpub.com'
    publisher.save()
    print(publisher.email)
    contributor = Contributor.objects.create(first_names="Rowel", last_names="Atienza",
                                             email="RowelAtienza@example.com")
    print(contributor)
    print('\n>>> END <<<')

manage.py:

import os
import sys
from crud_ops import *



def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings')
    try:
    from django.core.management import execute_from_command_line
except ImportError as exc:
    raise ImportError(
        "Couldn't import Django. Are you sure it's installed and "
        "available on your PYTHONPATH environment variable? Did you "
        "forget to activate a virtual environment?"
    ) from exc
execute_from_command_line(sys.argv)
crud_ops()


 if __name__ == '__main__':
  main()

settings.py:

from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'secret'
DEBUG = True

ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'reviews'
]
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 = 'bookr.urls'
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, "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 = 'bookr.wsgi.application'
DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': BASE_DIR / 'db.sqlite3',
}
}
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',
},
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True
STATIC_URL = '/static/'
Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
Avi
  • 25
  • 4
  • 1
    I don't know the issue; but I hope that ```SECRET_KEY``` is fake; otherwise, you'll need to regenerate your secret key. In the future, please redact your secret keys before posting. – ewokx Apr 16 '23 at 23:42
  • Does this answer your question? [ImproperlyConfigured: You must either define the environment variable DJANGO\_SETTINGS\_MODULE or call settings.configure() before accessing settings](https://stackoverflow.com/questions/26082128/improperlyconfigured-you-must-either-define-the-environment-variable-django-set) – Ivan Starostin Apr 17 '23 at 05:51
  • No it didn't but I figured it out thanks. – Avi Apr 19 '23 at 21:19

0 Answers0