Login

Auto-create Django admin user during syncdb

Author:
statico
Posted:
January 18, 2010
Language:
Python
Version:
1.1
Score:
9 (after 9 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

eriol (on June 14, 2010):

Nice snippet!

I'm using it in little different way: I put all the code, from create_superuser signal disconnection to create_testuser signal connection under a if setting.DEBUG and removed the check inside create_testuser. In this way when DEBUG == False you will be prompted for creation of a superuser.

#

basharov (on September 17, 2010):

Works perfect and saves me a lot of time, thanks!

#

Please login first before commenting.