[Django]-Django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured

10👍

You should call django.setup() before importing your models:

import os
import random
from faker import Faker

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myfirst.settings')
import django
django.setup()

from first_app.models import Topic, Webpage, AccessRecord

#...

0👍

I got recently a very similar error

ERROR project/tests/test_models.py - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are no...
ERROR project/tests/test_priced_offers.py - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings...

This happened, because I was running pytest in the root folder, not in the project folder. Error disappeared when I executed the tests in project folder.

Hope this is helpful to someone!

0👍

I just debug my populate.py file and found that i was importing the models.py before configuring Django so first you need to set environment then you need to setup Django and at last you can import models in populate.py file.

from faker import Faker
import random
import django
import os

# Configure settings for project
# Need to run this before calling models from application!
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_model.settings') # this should be done first.

# Import settings
django.setup() # This needs to be done after you set the environ

from first_app.models import Topic, WebPage, AccessRecord # At last you can import models in populate.py file


fakegen = 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):
    '''
    Create N Entries of Dates Accessed
    '''

    for entry in range(N):

        # Get Topic for Entry
        top = add_topic()

        # Create Fake Data for entry
        fake_url = fakegen.url()
        fake_date = fakegen.date()
        fake_name = fakegen.company()

        # Create new Webpage Entry
        webpg = WebPage.objects.get_or_create(
            topic=top, name=fake_name, url=fake_url,)[0]

        # Create Fake Access Record for that page
        # Could add more of these if you wanted...
        accRec = AccessRecord.objects.get_or_create(
            name=webpg, date=fake_date)[0]


if __name__ == '__main__':
    print("Populating the databases...Please Wait")
    populate(20)
    print('Populating Complete')

Leave a comment