Users in initial data fixture

后端 未结 6 1673
臣服心动
臣服心动 2021-01-31 01:50

I\'m creating a few users by default in my fixtures/initial_data.json so as to have some testing \"subjects.\" The problem I\'m experiencing is password generation.

6条回答
  •  一向
    一向 (楼主)
    2021-01-31 02:10

    Adding to the answer of @GauravButola, I created a custom management command to load the fixture and fix the passwords in one step. This is useful when not using a testing framework to do the setup of the passwords. The example is working with django 1.11 and probably earlier versions.

    In your app providing the fixture add your management command (this is python3 times, so I omitted the init pys):

    yourapp/
        models.py
        fixtures/
            initial_data.json
        management/
            commands/
                initdata.py
    

    With initdata.py looking like this:

    from django.core.management import BaseCommand, call_command
    from django.contrib.auth.models import User
    # from yourapp.models import User # if you have a custom user
    
    
    class Command(BaseCommand):
        help = "DEV COMMAND: Fill databasse with a set of data for testing purposes"
    
        def handle(self, *args, **options):
            call_command('loaddata','initial_data')
            # Fix the passwords of fixtures
            for user in User.objects.all():
                user.set_password(user.password)
                user.save()
    

    Now you can load your initial_data and have valid passwords by calling:

    ./manage.py initdata
    

提交回复
热议问题