添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

How to resolve django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS error?

Ask Question

I am getting this error when I try to run python3 poppulate_first_app.py file (using Kali Linux and venv with django 3.1.7).

Error...

Traceback (most recent call last):
  File "/home/hadi/Documents/first_django_project/poppulate_first_app.py", line 4, in <module>
    from first_app.models import *
  File "/home/hadi/Documents/first_django_project/first_app/models.py", line 6, in <module>
    class Topic(models.Model):
  File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config
    self.check_apps_ready()
  File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready
    settings.INSTALLED_APPS
  File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__
    self._setup(name)
  File "/home/hadi/Documents/first_django_project/venv/lib/python3.9/site-packages/django/conf/__init__.py", line 63, in _setup
    raise ImproperlyConfigured(
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.

I tried to run it on Windows too, but the same error, also I recreate the project in case I miss with settings or something, also I tried most of the answers posted here but none of them worked for me.

Here is my poppulate_first_app.py code:

import django
import random
from faker import Faker
from first_app.models import *
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_django_project.settings')
django.setup()
# FAKE POP SCRIPT
fake_gen = Faker()
topics = ['Search', 'Social', 'Marketplace', 'News', 'Games']
def add_topic():
    t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
    t.save()
    return t
def populate(n=5):
    for entry in range(n):
        # get the topic for the entry
        top = add_topic()
        # create the fake data for that entry
        fake_url = fake_gen.url()
        fake_date = fake_gen.date()
        fake_name = fake_gen.company()
        # create the new webpage entry
        webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0]
        # create a fake access record for that webpage
        acc_rec = AccessRecord(namme=webpg, date=fake_date)
if __name__ == '__main__':
    print('Populating script!')
    populate(20)
    print('Populating complete!')

Here is my settings.py code:

Django settings for first_django_project project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = BASE_DIR / 'templates' STATIC_DIR = BASE_DIR / 'static' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'f*7mcgl1l+4l@$qxf!xp*91l%*1^cl@@rp8&_m5upzr&4j_dqr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'first_app.apps.FirstAppConfig', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # import django # django.setup() 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 = 'first_django_project.urls' TEMPLATES = [ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR, ], '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 = 'first_django_project.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', # Password validation # https://docs.djangoproject.com/en/3.1/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.1/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.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR,

Here is my models.py code:

from django.db import models
# Create your models here.
class Topic(models.Model):
    top_name = models.CharField(max_length=264, unique=True)
    def __str__(self):
        return self.top_name
class Webpage(models.Model):
    topic = models.ForeignKey(Topic, on_delete=models.DO_NOTHING)
    name = models.CharField(max_length=264, unique=True)
    url = models.URLField(unique=True)
    def __str__(self):
        return self.name
class AccessRecord(models.Model):
    name = models.ForeignKey(Webpage, on_delete=models.DO_NOTHING)
    date = models.DateField()
    def __str__(self):
        return str(self.date)

Here is my wsgi.py code:

WSGI config for first_django_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_django_project.settings') application = get_wsgi_application() Try changing the following line in the wsgi.py file from: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_django_project.settings') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'poppulate_first_app.settings'). If that works, then remove that same line from the top of the poppulate_first_app.py file. – pheeper Mar 20, 2021 at 14:51 @pheeper poppulate_first_app.py is not a package it gave me the following error: ModuleNotFoundError: No module named 'poppulate_first_app.settings'; 'poppulate_first_app' is not a package – Hadi Ayoub Mar 20, 2021 at 15:10
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_django_project.settings')
django.setup()

before the from first_app.models import *

poppulate_first_app.py is a file not a module I can't access settings from it. Anyway, I tired it and this error was produced: ModuleNotFoundError: No module named 'poppulate_first_app.settings'; 'poppulate_first_app' is not a package – Hadi Ayoub Mar 20, 2021 at 12:52

You get this error when you are running python on the terminal instead of running python manage.py shell.

If you are running the python, on terminal, you have to manually set DJANGO_SETTTINGS_MODULE environment variable so that django knows where to find your settings.

When you use python manage.py shell, this is automatically done for you.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.