Equivalent of get_or_create for adding users

后端 未结 4 1823
北荒
北荒 2021-02-07 02:05

Is there a simpler way to add a user than with the following pattern?

    try:
        new_user = User.objects.create_user(username, email, password)
    except          


        
4条回答
  •  醉话见心
    2021-02-07 02:50

    This method should solve this problem but keep in mind that in the database, password is kept as a hash of the password, and as pointed before, "get_or_create" makes an exact lookup. So before the lookup actually happens, we "pop" the password from the kwargs. This method on your custom UserManager:

    def get_or_create(self, defaults=None, **kwargs):
        password = kwargs.pop('password', None)
        obj, created = super(UserManager, self).get_or_create(defaults, **kwargs)
        if created and password:
            obj.set_password(password)
            obj.save()
        return obj, created
    

提交回复
热议问题