Search code examples
djangodjango-modelsdjango-signals

In Django create a dummyuser (on startup?)


My goal is to have one dummyuser in the database. I already wrote the following function

def get_test_user():
    user, created = get_user_model.objects.get_or_create(username=TESTUSER_USERNAME)
    user.set_password(TESTUSER_PASSWORD)
    user.save

But where and how should I call it to achieve my goal. I am aware that testing django will create its own database and that there are functions for creating test users. But this should actually run in the production database as well.


Solution

  • You can create data migration, for example:

    from django.contrib.auth.hashers import make_password
    from django.db import migrations
    
    
    def create_user(apps, schema_editor):
        User = apps.get_registered_model('auth', 'User')
        user = User(
            username='user',
            email='user@mail.com',
            password=make_password('pass'),
            is_superuser=False,
            is_staff=False
        )
        user.save()
    
    
    class Migration(migrations.Migration):
        dependencies = [
            ('auth', '0001_initial')
        ]
    
        operations = [
            migrations.RunPython(create_user),
        ]