Wednesday, April 13, 2022

[FIXED] How to make migrations for a reusable Django app?

Issue

I am making a reusable Django app without a project. This is the directory structure:

/
/myapp/
/myapp/models.py
/myapp/migrations/
/myapp/migrations/__init__.py

When I run django-admin makemigrations I get the following error:

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Obviously, this is because I don't have a settings module configured, because this is a reusable app. However, I would still like to ship migrations with my app. How can I make them?


Solution

Actually, you don't need to have project, all you need is settings file and script, that runs migrations creation. Settings must contain folowing (minimum):

# test_settings.py

DEBUG = True

SECRET_KEY = 'fake-key'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'your_app'
]

And the script, that makes migrations should look like this:

# make_migrations.py

import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings")
    from django.core.management import execute_from_command_line
    args = sys.argv + ["makemigrations", "your_app"]
    execute_from_command_line(args)

and you should run it by python make_migrations.py. Hope it helps someone!



Answered By - Compadre
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.