I encountered an AUTH_USER_MODEL error while trying to populate my database with fake data?

I wanted to populate my database for testing purposes, so after doing some research, I came across a tool called FactoryBoy. I decided to use it in conjunction with Pandas to extract data from a CSV file and load it into my database. After writing the code, I gave it a try. Initially, I faced some configuration issues, particularly with defining the correct path, as I was running the script directly without using manage.py. Eventually, I encountered an error that I couldn’t resolve, as I couldn’t define the source.

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed

Here’s how my project is structured:

My_workspace
  --api
    --users
	  ---__init__.py
	  ---admin.py
	  ---apps.py
	  ---factories.py
	  ---forms.py
	  ---models.py
	  ---populate_db.py
	  ---serializers.py
	  ---tests.py
	  ---urls.py
	  ---views.py
    --my_project
   	  ---settings.py
   	  ---env

Initially, I encountered exceptions stating that the users package didn’t exist, even though the directory structure was exactly as described in the documentation. To resolve this, I used a tool called setuptools to help Django recognize the users directory as a package. I added two modules: factories.py and populate_db.py.

# factories.py
import os 
import django
from pathlib import Path
from dotenv import load_dotenv

# Load environment variables from .env
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent.parent

# Load environment variables from .env (if used)
dotenv_path= BASE_DIR /'My_workspace/api/my_project/.env'
load_dotenv(dotenv_path=dotenv_path)

# Manually set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings')

# Initialize Django
django.setup()

import factory
from users.models import User
from django.contrib.auth import get_user_model

User = get_user_model()


class UserFactory(factory.django.DjangoModelFactory):  # For Django
    class Meta:
        model = User
		#added the fields 
# populate_db.py
    import pandas as pd
    from factories import UserFactory  # Adjust import path accordingly
    
    def populate_from_csv(file_path):
        # Read the CSV file
        data = pd.read_csv(file_path)
        
        # Iterate over each row and create a user instance
        for _, row in data.iterrows():
            UserFactory(#added the fields)
        print("Database successfully populated!")
        
    # Run the script
    path = "path to the script"
    if __name__ == "__main__":
        populate_from_csv(path)
#settings.py
    # Application definition
    AUTH_USER_MODEL = "users.User"
    
    INSTALLED_APPS = [
        "users"
    ]
#env
    SECRET_KEY=my secret key
    DEBUG=false
    DB_USER=user
    DB_PASSWORD=pass
    DB_NAME=database
    DB_HOST=localhost 
    DB_PORT=5432 

I added the users module to the INSTALLED_APPS environment variable, but I’m still encountering this error. Do you have any suggestions on how to fix it?

My recommendation in all situations like this is to work with Django, don’t try to work around it.

Create your script as a custom management command and use the manage.py file to run it.