How to load sql fixture in Django for User model? How to load sql fixture in Django for User model? django django

How to load sql fixture in Django for User model?


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.


You are looking for loaddata:

manage.py loadata path/to/your/fixtureFile

But I think the command can only deal with files in XML, YAML, Python or JSON format (see here). To create such appropriate files, have a look at the dumpdata method.


There is a trick for this: (tested on Django 1.3.1)

Solution:

  1. python manage.py startapp auth_fix
  2. mkdir auth_fix/fixtures
  3. python manage.py dumpdata auth > auth_fixtures/fixtures/initial_data.json
  4. Include auth_fix in INSTALLED_APPS inside settings.py

Next time you run python manage.py syncdb, Django will load the auth fixture automatically.

Explanation:

  1. Just make an empty app to hold the fixtures folder. Leave __init__py, models.py and views.py in it so that Django recognizes it as an app and not just a folder.
  2. Make the fixtures folder in the app.
  3. python manage.py dumpdata auth will dump the "auth" data in the DB with all the Groups and Users information. The rest of the command simply redirects the output into a file called "initial_data.json" which is the one that Django looks for when you run "syncdb".
  4. Just include auth_fix in INSTALLED_APPS inside settings.py.

This example shows how to do it in JSON but you can basically use the format of your choice.