This avoids the frustrating step of having to set up a new admin user every time you re-initialize your database.
Put this in any models
module. In this example I use common.models
.
Adapted from http://stackoverflow.com/questions/1466827/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #!/usr/bin/env python
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.contrib.auth.management import create_superuser
from django.db.models import signals
# From http://stackoverflow.com/questions/1466827/ --
#
# Prevent interactive question about wanting a superuser created. (This code
# has to go in this otherwise empty "models" module so that it gets processed by
# the "syncdb" command during database creation.)
signals.post_syncdb.disconnect(
create_superuser,
sender=auth_models,
dispatch_uid='django.contrib.auth.management.create_superuser')
# Create our own test user automatically.
def create_testuser(app, created_models, verbosity, **kwargs):
if not settings.DEBUG:
return
try:
auth_models.User.objects.get(username='test')
except auth_models.User.DoesNotExist:
print '*' * 80
print 'Creating test user -- login: test, password: test'
print '*' * 80
assert auth_models.User.objects.create_superuser('test', '[email protected]', 'test')
else:
print 'Test user already exists.'
signals.post_syncdb.connect(create_testuser,
sender=auth_models, dispatch_uid='common.models.create_testuser')
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Nice snippet!
I'm using it in little different way: I put all the code, from
create_superuser
signal disconnection tocreate_testuser
signal connection under aif setting.DEBUG
and removed the check insidecreate_testuser
. In this way whenDEBUG == False
you will be prompted for creation of a superuser.#
Works perfect and saves me a lot of time, thanks!
#
Please login first before commenting.