Arishta
Arishta

Reputation: 174

django.core.exceptions.ImproperlyConfigured error: Requested setting INSTALLED_APPS, but settings are not configured

Background:

I am working on a microservices project that consists of two apps: Django app(admin app) and Flask app(main app). Each of these runs on a Docker container. The error occurred as I was trying to implement a functionality that whenever a product is liked in the main app, the information is passed on to the admin app via RabbitMQ, so that the likes could also get updated in its database.

I keep getting this error in the admin app, because of which the likes are not updated in the database of the admin app.

Project structure of Django (Admin) app

It consists of one app - Products.

Django app structure

Error details:


 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.

Error screenshot

Relevant files:

Here is the consumer.py file of the admin app.

from products.models import Product
import pika
import json
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin.settings")
django.setup()

params = pika.URLParameters(
    'amqps://mynfehiw:[email protected]/mynfehiw')


connection = pika.BlockingConnection(params)

channel = connection.channel()

channel.queue_declare(queue='admin')


def callback(ch, method, properties, body):
    print('Received in admin')
    id = json.loads(body)
    print(id)
    product = Product.objects.get(id=id)
    product.likes = product.likes + 1
    product.save()
    print('Product likes increased!')


channel.basic_consume(
    queue='admin', on_message_callback=callback, auto_ack=True)

print('Started Consuming')

channel.start_consuming()

channel.close()

Here is the manage.py file in the admin app:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'admin.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)


if __name__ == '__main__':
    main()

Here is the wsgi.py file in the admin app:

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

Here is the settings.py file in admin:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'h_j39)qml90o2ir!fo(h2w_4&3$_cy=)7ak2at=d6yo(st9png'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'products'
]

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

ROOT_URLCONF = 'admin.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'admin.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'db',
        'PORT': '3306',
    }
}

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/'
CORS_ORIGIN_ALLOW_ALL = True

Things already tried:

  1. After reading the other answers on StackOverflow, I included this piece of code:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin.settings")
django.setup()

in the consumer.py file. However, this does not seem to work.

  1. I ran my Docker container using docker compose up and wrote this command on the other terminal.
set DJANGO_SETTINGS_MODULE=admin.settings

This does not work either.

Could you give any idea on how to resolve this error?

Upvotes: 0

Views: 5927

Answers (1)

Som-1
Som-1

Reputation: 661

Try to import Product after setting up django:

import pika
import json
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin.settings")
django.setup()

from products.models import Product

...

When you import modules in python their code gets executed: imports are perfomed, classes and variables are defined, etc. Django project files like models usually import some django modules which try to read settings when used. And it's not initialized at the moment!

So you need to initialize django first, then import models.

Upvotes: 3

Related Questions