How to load sql fixture in Django for User model?

aldux picture aldux · Mar 9, 2010 · Viewed 15.9k times · Source

Does anyone knows how to load initial data for auth.User using sql fixtures? For my models, I just got have a < modelname >.sql file in a folder named sql that syncdb does it's job beautifully. But I have no clue how to do it for the auth.User model. I've googled it, but with no success.

Thanks in advance,

Aldo

Answer

Derek Dahmer picture Derek Dahmer · Feb 23, 2011

For SQL fixtures, you'd have to specifically have insert statements for the auth tables. You can find the schema of the auth tables with the command python manage.py sql auth.

The much easier and database-independent way (unless you have some additional SQL magic you want to run), is to just make a JSON or YAML fixture file in the fixtures directory of your app with data like this:

- model: auth.user
  pk: 100000
  fields:
    first_name: Admin
    last_name: User
    username: admin
    password: "<a hashed password>"

You can generate a hashed password quickly in a django shell

>>> from django.contrib.auth.models import User
>>> u = User()
>>> u.set_password('newpass')
>>> u.password
'sha1$e2fd5$96edae9adc8870fd87a65c051e7fdace6226b5a8'

This will get loaded whenever you run syncdb.