Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make migrations for a reusable Django app?

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?

like image 760
Jaap Joris Vens Avatar asked May 30 '16 14:05

Jaap Joris Vens


People also ask

How do I recreate migrations in Django?

Django's migration can be reset by cleaning all the migration files except __init__.py files under each project app directory, followed by dropping the database and creating migration again using python manage.py makemigrations and python manage.py migrate .

What is the difference between Makemigrations and migrate in Django?

migrate , which is responsible for applying and unapplying migrations. makemigrations , which is responsible for creating new migrations based on the changes you have made to your models.


1 Answers

Real Python has a tutorial on writting a reusable Django App.

The chapter Bootstrapping Django Outside of a Project has a very interesting example:

#!/usr/bin/env python
# boot_django.py

"""
This file sets up and configures Django. It's used by scripts that need to
execute as if running in a Django server.
"""

import os

import django
from django.conf import settings


BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "your_app"))


def boot_django():

    settings.configure(
        BASE_DIR=BASE_DIR,
        DEBUG=True,
        DATABASES={
            "default":{
                "ENGINE":"django.db.backends.sqlite3",
                "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
            }
        },
        INSTALLED_APPS=(
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "your_app",
        ),
        TIME_ZONE="UTC",
        USE_TZ=True,
    )

    django.setup()

And then:

#!/usr/bin/env python
# makemigrations.py

from django.core.management import call_command
from boot_django import boot_django

boot_django()
call_command("makemigrations", "your_app")
like image 95
raratiru Avatar answered Oct 04 '22 03:10

raratiru