How to create a user in Django?

后端 未结 4 888
不思量自难忘°
不思量自难忘° 2020-12-12 18:37

I\'m trying to create a new User in a Django project by the following code, but the highlighted line fires an exception.

def createUser(request):
    userNam         


        
4条回答
  •  萌比男神i
    2020-12-12 19:11

    Bulk user creation with set_password

    I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

    set_password is another way to generate the hashed passwords:

    def users_iterator():
        for i in range(nusers):
            is_superuser = (i == 0)
            user = User(
                first_name='First' + str(i),
                is_staff=is_superuser,
                is_superuser=is_superuser,
                last_name='Last' + str(i),
                username='user' + str(i),
            )
            user.set_password('asdfqwer')
            yield user
    
    class Command(BaseCommand):
        def handle(self, **options):
            User.objects.bulk_create(iter(users_iterator()))
    

    Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

    Tested in Django 1.9.

提交回复
热议问题