Are you trying to figure out a simple and effective way to create hundreds or thousands of fake users in order to test your Django application? If so, I’m gonna explain how I did it, and I hope to save you time and headache… but first, a little preface:
Django ships with a pretty cool fixtures mechanism, a fixture is merely row data that can be automatically loaded into the database.
It’s possible to create a fixture manually (in JSON or YAML format) or dump database tables into fixtures using a shell command (dumpdata).
There is also an helper method in the ORM layer which allows to insert multiple objects in the database in a single
shot query (without to have to call save() for each object and by skipping all the related pre-save/post-save signals dispatchment): bulk_create().
That said, these are the steps to replicate what I did to reach the goal:
1. In my application I created an user “FakeUser” with a password “FakePassword” (you can obviously choose the one you prefer)
2. I saved the hashed password from the database (the user has been previously created in order to get an hashed password for which we know the raw version)
3. I wrote a python script to generate N users (where N is the desired number of records) with dynamically generated names and data:
from myapp.User import User
users = 
for i in range(100):
user = User(firstName='User%dFirstName' % i,
lastName='User%dLastName' % i,
username='user%d' % i,
email@example.com' % i,
sex=1 if i % 2 == 0 else 2)
If you are wondering about names of fields I configured, remember that I’m using a custom User model (a feature introduced in Django 1.5). Anyway the script above creates 100 users objects and save the related 100 records in the database using User.objects.bulk_create(). All the fields have been configured dynamically, except the password, that will be the same (“FakePassword”) for each user, since they are fake users and we don’t actually need different passwords for our test purposes.
In order to run the script above I opened an interactive shell:
python manage.py shell
and I executed the file:
4. Once the records have been created I dumped the data into a JSON fixture:
python manage.py dumpdata myapp.User > /myapp/fixtures/initial_data.json
dumpdata wants the name of the model object for which to dump data (prefixed by the name of the app it belongs to). The command returns a JSON string, so we can use the output redirection (>) to write a file called “initial_data.json”. This name is not casual, in fact Django will looks for fixtures named “initial_data” in order to prepopulate tables with given data during syncdb. Now, since we have this helpful fixture we could drop the database and regenerate it to let Django autofill the user records… cool, do you agree?