Login

Auto-create Django admin user during syncdb

Author:
statico
Posted:
January 18, 2010
Language:
Python
Version:
1.1
Tags:
user automatic admin django admin-user manage syncdb adminuser
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', 'x@x.com', '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. Configurable defaults for contrib.sites default Site during syncdb by chrischambers 3 years, 7 months ago
  2. backupdb command by msaelices 6 years, 9 months ago
  3. Post-post-syncdb and post-post-migrate by theY4Kman 2 days, 13 hours ago
  4. UUIDField oriented django User by bwhittington 5 years, 11 months ago
  5. Improved User Admin by gregb 4 years, 11 months 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.