How to do migrations for a reusable Django application?

I am making a reusable Django application 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 do not have a customized settings module, because it is a reusable application. However, I would still like to migrate migrations using my application. How can I make them?

+8
source share
3 answers

To perform the migration, you need a functional Django project (with the application you installed).

A common way to do this is to create a β€œtest” project that contains simple Django project tasks that you can perform for migration, etc. Migrations will be created in the right place inside your application directory, so you can still have the correct version control, etc. in your own reusable application.

Migrations created in this way will be self-sufficient (if your models are independent of the models of other applications) and can be sent as part of your packaged, reusable application.

Many of the larger Django-based projects actually send a test project as part of their code, so developers can quickly launch it to test applications and perform migrations, etc.

+12
source

In fact, you do not need to have a project, all you need is a settings file and a script that starts the migration creation. Settings should contain the following (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 does the migration 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 python make_migrations.py . Hope this helps someone!

+13
source

Create settings file:

 SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'your_app' ] 

then

 export DJANGO_SETTINGS_MODULE=yourapp.migrations_settings django-admin makemigrations yourapp 
0
source

All Articles