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.
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
- [Django]-Python/Django: how to assert that unit test result contains a certain string?
- [Django]-When saving, how can you check if a field has changed?
- [Django]-Django DRF with oAuth2 using DOT (django-oauth-toolkit)
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/
- [Django]-Temporarily disable auto_now / auto_now_add
- [Django]-Celery discover tasks in files with other filenames
- [Django]-Django's self.client.login(β¦) does not work in unit tests
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. π
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-Django character set with MySQL weirdness
- [Django]-ImproperlyConfiguredError about app_name when using namespace in include()
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.
- easy_install south
- 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β¦
- [Django]-How to detect Browser type in Django?
- [Django]-Django's self.client.login(β¦) does not work in unit tests
- [Django]-Django simple_tag and setting context variables
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.
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django MEDIA_URL and MEDIA_ROOT
- [Django]-How about having a SingletonModel in Django?
5π
The manage.py reset
command will reset your database without destroying your created super user. Data does however need to be re-imported.
- [Django]-How can I handle Exceptions raised by dango-social-auth?
- [Django]-What does Django's @property do?
- [Django]-Using Cloudfront with Django S3Boto
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.
- [Django]-Django render_to_string missing information
- [Django]-'pip' is not recognized as an internal or external command
- [Django]-Django REST Framework (DRF): Set current user id as field value
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!
- [Django]-Why is factory_boy superior to using the ORM directly in tests?
- [Django]-Django apps aren't loaded yet when using asgi
- [Django]-Python + Django page redirect
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)]
- [Django]-Gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django
- [Django]-How do I use Django templates without the rest of Django?
- [Django]-Execute code when Django starts ONCE only?
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.
- [Django]-Foreign key from one app into another in Django
- [Django]-How to assign items inside a Model object with Django?
- [Django]-Django admin: how to sort by one of the custom list_display fields that has no database field
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')
- [Django]-Set up a scheduled job?
- [Django]-Unit testing with django-celery?
- [Django]-Django unit tests without a db
1π
My solution to this was to just not delete that auth tables when wiping out my database.
- [Django]-Define css class in django Forms
- [Django]-How to disable Django's CSRF validation?
- [Django]-Use Python standard logging in Celery
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.
- [Django]-Cron and virtualenv
- [Django]-Problems with contenttypes when loading a fixture in Django
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
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.
- [Django]-Django β query filter on manytomany is empty
- [Django]-How do I clone a Django model instance object and save it to the database?
- [Django]-How to set up a PostgreSQL database in Django