Andy McKay

Nov 17, 2008

syncdb and Django

This has cropped up a couple of times on irc, so here's a recipe I have for restarting my Django instance during development. I'm not the sort of person who takes a long time to think it all through and can write a model and call it done, I iterate quickly and often. For the quickest way to do that during the initial development, I drop the db, re run syncdb and import my fixtures regularly.

Once a production version is out and running I then get rid of this script and do migrations.

There's no easy way from the command line to create a user neither syncdb --noinput or createsuperuser --noinput accept a password. Leaving lazy people like me wanting. I used to use pexpect but I find just creating a user object nice and easy. So for a project called collector, the following works well for me:

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"

# dump the data to fixtures
os.system('python dumpdata collector --indent=2 > collector/models/fixtures/data.json')
# drop and recreate the db (this is for postgres)
os.system('dropdb authy')
os.system('createdb authy --encoding=UTF-8')
# sync the db
os.system('python syncdb --noinput')

# create a super user
from django.contrib.auth.models import User
u = User.objects.create(
print "User account created"

# load the fixtures back in
os.system('python loaddata data.json')
# run the server
os.system('python runserver')

I can then quickly get in the cycle of creating a model, entering data in admin interface, dumping it to a fixture and then writing unit tests.