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
Ask Question
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.
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.
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:zXmApSaqRu8AJo3oTmJTxGzzEo8KTs6F@lionfish.rmq.cloudamqp.com/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')
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:
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.
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?
–
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.
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.