When creating sample data (possibly after we have manually insert it the minimum data to see the functionality of the site) we should generally flush the database to preserve its structure but clear all the contents.
We can do this with the python manage.py flush command. It is useful to put the command as part of a script to manage the data as we work on the site:
import os
import django
from django.core.management import call_command
# Load settings.
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
django.setup()
# Flush current data.
call_command("flush", "--noinput")
print("Flushed existing db.")
# Create a superuser.
os.environ["DJANGO_SUPERUSER_PASSWORD"] = "fake_pw"
cmd = "createsuperuser --username fake_admin"
cmd += " --email fake_email@example.com"
cmd += " --noinput"
cmd_parts = cmd.split()
call_command(*cmd_parts)The env variable DJANGO_SETTINGS_MODULE is used to tell Django what our settings file is (settings.py in this case). Then we use django.setup(). The call_command() function allows us to run management commands through a script, such as flush.
To create a superuser account for testing we have to remember that Django only reads passwords from environment variables. Thus we set the appropriate var, and then build a command to create a superuser.