[Django]-Automatically create an admin user when running Django's ./manage.py syncdb

80πŸ‘

βœ…

I know the question has been answered already but …

A Much simpler approach is to dump the auth module data into a json file once the superuser has been created:

 ./manage.py dumpdata --indent=2 auth > initial_data.json

You can also dump the sessions data:

./manage.py dumpdata --indent=2 sessions

You can then append the session info to the auth module dump (and probably increase the expire_date so it does not expire… ever ;-).

From then, you can use

/manage.py syncdb --noinput

to load the superuser and his session when creating the db with no interactive prompt asking you about a superuser.

πŸ‘€philgo20

49πŸ‘

Instead of deleting your entire database, just delete the tables of your app before running the syncdb

This will accomplish it for you in a single line (per app):

python manage.py sqlclear appname | python manage.py dbshell

The first command will look at your app and generate the required SQL to drop the tables. This output is then piped to the dbshell to execute it.

After its done, run your syncdb to recreate the tables:

python manage.py syncdb
πŸ‘€Andre Miller

29πŸ‘

The key is to use --noinput at the time of syncdb & then use this one liner to create superuser

echo "from django.contrib.auth.models import User; User.objects.create_superuser('myadmin', 'myemail@example.com', 'hunter2')" | python manage.py shell

Credit : http://source.mihelac.org/2009/10/23/django-avoiding-typing-password-for-superuser/

πŸ‘€user

16πŸ‘

If you want the ability β€” as I do β€” to really start with a fresh database without getting asked that superuser question, then you can just de-register the signal handler that asks that question. Check out the very bottom of the file:

django/contrib/auth/management/__init__.py

to see how the registration of the superuser function gets performed. I found that I could reverse this registration, and never get asked the question during β€œsyncdb”, if I placed this code in my β€œmodels.py”:

from django.db.models import signals
from django.contrib.auth.management import create_superuser
from django.contrib.auth import models as auth_app

# 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_app,
    dispatch_uid = "django.contrib.auth.management.create_superuser")

I am not sure how to guarantee that this code gets run after the Django code that does the registration. I had thought that it would depend on whether your app or the django.contrib.auth app gets mentioned first in INSTALLED_APPS, but it seems to work for me regardless of the order I put them in. Maybe they are done alphabetically and I’m lucky that my app’s name starts with a letter later than β€œd”? Or is Django just smart enough to do its own stuff first, then mine in case I want to muck with their settings? Let me know if you find out. πŸ™‚

11πŸ‘

I’ve overcome this feature using south

Its a must have for any django developer.

South is a tool designed to help migrate changes over to the live site without destroying information or database structure. The resulting changes can be tracked by south and using the generated python files – can perform the same actions on an alternative database.

During development, I use this tool to git track my database changes – and to make a change to the database without the need to destroy it first.

  1. easy_install south
  2. Add β€˜south’ to your installed apps

Proposing first time run of south on an app.

$ python manage.py schemamigration appname --init

This will initiate schema detection on that app.

$ python manage.py migrate appname

This will apply the model changes

  • The database will have the new models.

Changing a model after the first run

$ python manage.py schemamigration appname --auto

$ python manage.py migrate appname


Models will have changed – data is not destroyed.
Plus south does much more…

πŸ‘€Glycerine

9πŸ‘

Note: since version 1.7 syncdb command is deprecated. Use migrate instead.

Also Django 1.7 introduced AppConfig as means of customizing applications’ initialization process.

Thus since Django 1.7 the simplest way to achieve what you want is to employ an AppConfigβ€˜s subclass.

Let say, you happen to have your own example_app that is added to your INSTALLED_APPS and you want to create and admin user with admin password whenever you run ./manage.py migrate from scratch. I also assume that automatic admin user creation is required only in dev environment – not in production.

Add the following code to example_app/apps.py

# example_app/apps.py

from django.apps import AppConfig
from django.conf import settings
from django.db.models.signals import post_migrate
from django.contrib.auth.apps import AuthConfig


USERNAME = "admin"
PASSWORD = "admin"


def create_test_user(sender, **kwargs):
    if not settings.DEBUG:
        return
    if not isinstance(sender, AuthConfig):
        return
    from django.contrib.auth.models import User
    manager = User.objects
    try:
        manager.get(username=USERNAME)
    except User.DoesNotExist:
        manager.create_superuser(USERNAME, 'x@x.com', PASSWORD)


class ExampleAppConfig(AppConfig):
    name = __package__

    def ready(self):
        post_migrate.connect(create_test_user)

Also add the following reference to the app configuration inside apps example_app/__init__.py:

# example_app/__init__.py

default_app_config = 'example_app.apps.ExampleAppConfig'

Where the default_app_config is a string Python path to the AppConfig subclass as mentioned here.

πŸ‘€Archibald

5πŸ‘

The manage.py reset command will reset your database without destroying your created super user. Data does however need to be re-imported.

πŸ‘€tjb

3πŸ‘

You can use django-finalware to do this for you. Just add finalware to your INSTALLED_APPS and include the following in your settings.py:

SITE_SUPERUSER_USERNAME = 'myadmin'
SITE_SUPERUSER_EMAIL = 'myadmin@example.com'
SITE_SUPERUSER_PASSWORD  = 'mypass'  # this can be set from a secret file.

# optional object id. Ensures that the superuser id is not set to `1`.
# you can use this as a simple security feature
SITE_SUPERUSER_ID = '343'

Then just run ./manage.py syncdb (Django <1.7) or ./manage.py migrate (Django >= 1.7), and it will automatically create a superuser or update the existing one for you.

You are never prompted to created a superuser anymore.

πŸ‘€Val Neekman

3πŸ‘

I have resolved creating a python script like this one to reset all my stuff [updated version][1.8 too]:

import os
import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings.dev")

from django.conf import settings
from django.core import management
from django import get_version

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
if PROJECT_ROOT not in sys.path:
    sys.path.append(PROJECT_ROOT)

yn = raw_input('Are you sure you want to reset everything? (y/n) ')
if yn == 'y':

    # Drops the db / creates the db
    if settings.DATABASES['default']['ENGINE'].find('mysql') != -1:
        os.system('mysqladmin -uroot -pIronlord0 -f drop db')
        os.system('mysqladmin -uroot -pIronlord0 -f create db')
    elif settings.DATABASES['default']['ENGINE'].find('psycopg2') != -1:
        os.system('psql -U postgres -c "DROP DATABASE db"')
        os.system('psql -U postgres -c "CREATE DATABASE db WITH OWNER = admin"')
    elif settings.DATABASES['default']['ENGINE'].find('sqlite3') != -1:
        try:
            os.remove(os.path.join(PROJECT_ROOT, 'data.db'))
        except:
            pass

    # Getting application handle here otherwise db gets allocated and it can not be destroyed.
    if get_version() > '1.6.10':
        from django.core.wsgi import get_wsgi_application
        application = get_wsgi_application()

    management.call_command('syncdb', interactive=False)

    # Creates admin/password
    from django.contrib.auth.management.commands import changepassword
    management.call_command('createsuperuser', interactive=False, username="admin", email="xxx@example.com")
    command = changepassword.Command()
    command._get_pass = lambda *args: 'password'
    if get_version() >= '1.8':
        command.execute(username="admin")
    else:
        command.execute("admin")


    # Creates the default site entry
    from django.contrib.sites.models import Site
    site = Site.objects.get_current()
    site.domain = 'www.example.com'
    site.name = ' xxx '
    site.save()

it works like a charm!

P.S.: Be sure to stop your (testing) server where above db is in charge before running this script!

3πŸ‘

Since Django 1.7 the suggested way of populating the database is through data migrations. To create a data migration for creating the admin you should first create an empty migration:

./manage.py makemigrations --empty myapp --name create-superuser

This will create an empty migration in myapp/migrations/000x__create-superuser.py. Edit the file to make it look like this:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.contrib.auth.models import User


def create_superuser(apps, schema_editor):
    User.objects.create_superuser(username='myadmin', password='mypassword', email='myemail@gmail.com')


class Migration(migrations.Migration):

    dependencies = [('myapp', '000y_my-previous-migration-file'),]

    operations = [migrations.RunPython(create_superuser)]
πŸ‘€Sdra

2πŸ‘

Take a look at the dumpdata management command. For instance:

python manage.py dumpdata > initial_data.json

If this file, called a fixture, is named initial_data (.xml or .json), then the syncdb command will pick it up and populate your tables accordingly. It will still ask you if you want to create a user, but I believe you may safely answer β€œno”, after which point it will populate the database based on your fixture.

More info on this can be found in the docs.

πŸ‘€Ryan Duffield

2πŸ‘

Developing with sqlite.
Clear database by deleting file.
Load admin from fixtures.

change manage.py (django 1.4):

# hack to prevent admin promt
if  len(sys.argv) == 2 and sys.argv[1] == 'syncdb':
    sys.argv.append('--noinput')
πŸ‘€Cjkjvfnby

1πŸ‘

My solution to this was to just not delete that auth tables when wiping out my database.

πŸ‘€priestc

1πŸ‘

If you prefer to type initializing code direct into python source file, this code modified manage.py might help (and thanks for Cjkjvfnby’s little code!):

#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    # set your django setting module here
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") 

    from django.core.management import execute_from_command_line

    # hack to prevent admin prompt
    if len(sys.argv) == 2 and sys.argv[1] == 'syncdb':
        sys.argv.append('--noinput')

    execute_from_command_line(sys.argv)

    # additional process for creation additional user, misc data, and anything
    for arg in sys.argv:
        # if syncdb occurs and users don't exist, create them
        if arg.lower() == 'syncdb':
            print 'syncdb post process...'
            from django.contrib.auth.models import User

            admin_id = 'admin'
            admin_email = 'superuser@mail.com'
            admin_password = 'superuser_password'
            additional_users = [
                                ['tempuser', 'user_email@mail.com', 'tempuser_password']
                                ]

            # admin exists?
            user_list = User.objects.filter(username=admin_id)
            if len(user_list) == 0: 
                print 'create superuser: ' + admin_id
                new_admin = User.objects.create_superuser(admin_id, admin_email, admin_password)

            # additional user exists?
            for additional_user in additional_users:
                user_list = User.objects.filter(username=additional_user[0])
                if len(user_list) == 0: 
                    print 'create additional user: ' + additional_user[0]
                    new_admin = User.objects.create_user(additional_user[0], additional_user[1], additional_user[2])

            # any other data

I’m just showing the user creation code here, but you can enhance this code more as you want.

πŸ‘€Kenial

0πŸ‘

I’m using sqlite as a dev database. After changing model classes, just drop the corresponding tables with sqlite manager (a firefox plugin, open to inspect the data anyways) and run manage.py syncdb to recreate what’s missing.

πŸ‘€yanchenko

Leave a comment