PROJECTS NOTES HOME

Django management commands and an example with recreating migrations

1 Quick summary

  • Outside of your project directory, create a folder called helpers
  • Inside of that folder, two files: cleanup.cmd and empty_migration_folder.cmd
  • Run this script from manage.py location like so: ..\helpers\cleanup.cmd

2 Step 1 - create cleanup.cmd file

Inside of the app/management/commands directory.

It's content:

echo ======================#  Deleting database file
del db.sqlite3
echo Database file deleted successfully.

echo ======================#  Removing Django migrations
call ..\helpers\empty_migration_folder.cmd app

cd ../mysite
echo ======================#  Applying Django migrations from scratch
py manage.py makemigrations
py manage.py migrate

echo ======================#  Creating Django root user
py manage.py create_root_user

echo ======================#  Runserver
py manage.py runserver

echo ======================#  Finished

3 Step 2 - create empty_migration_folder.cmd file

Inside of the app/management/commands directory.

@echo off
set "folder=..\mysite\%1\migrations"

for /r "%folder%" %%F in (*) do (
    if not "%%~nxF"=="__init__.py" (
	del "%%F" /q
    )
)

for /d %%D in ("%folder%\*") do (
    if not "%%~nxD"=="__init__py" (
	rd "%%D" /s /q
    )
)

4 Step 3 - create create create_root_user.py file

Inside of the app/management/commands directory.

import os
from django.contrib.auth.models import User, Group
from django.core.management.base import BaseCommand

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
        username = 'root'
        password = 'hellothisispassword'

        user, created = User.objects.get_or_create(username=username)
        if created:
            user.set_password(password)
            user.is_staff = True
            user.is_superuser = True
            user.save()
            self.stdout.write(self.style.SUCCESS(
                f'Management user "{username}" created successfully'
            ))
        else:
            self.stdout.write(self.style.WARNING(
                f'Management user "{username}" already exists'
            ))