gpt4 book ai didi

python - 如何在自定义用户模型 Django 中修复 "Invalid password format or unknown hashing algorithm."

转载 作者:行者123 更新时间:2023-12-03 22:07:04 25 4
gpt4 key购买 nike

模型.py

class UserManager(BaseUserManager):

def create_user(self, phone, password=None):
if not phone:
raise ValueError('Please provide a valid Phone')

user = self.model(
phone = phone,
)
user.set_password(password)
user.save(using=self._db)
return user

def create_staffuser(self, phone, password):
user = self.create_user(
phone,
password=password,
)
user.staff = True
user.save(using=self._db)
return user

def create_superuser(self, phone, password):
user = self.create_user(
phone,
password=password,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user

phone_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}',
message="Phone number should be in the format '+9999999999', Up to 14 digits allowed.")


class User(AbstractBaseUser):

phone = models.CharField(validators=[phone_regex],max_length=15,unique=True)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False)
admin = models.BooleanField(default=False)

USERNAME_FIELD = 'phone'
REQUIRED_FIELDS = []

objects = UserManager()

def __str__(self):
return self.phone

def has_perm(self, perm, obj=None):
return True

def has_module_perms(self, app_label):
return True

@property
def is_staff(self):
return self.staff

@property
def is_admin(self):
return self.admin

@property
def is_active(self):
return self.active

admin.py
class UserCreationForm(forms.ModelForm):

password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

class Meta:
model = User
fields = ('phone',)

def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2

def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user


class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()

class Meta:
model = User
fields = ('phone', 'password')

def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]


class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm

# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('phone', 'admin')
list_filter = ('admin',)
fieldsets = (
(None, {'fields': ('phone', 'password')}),
('Personal info', {'fields': ()}),
('Permissions', {'fields': ('admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('phone', 'password1', 'password2')}
),
)
search_fields = ('phone',)
ordering = ('phone',)
filter_horizontal = ()

admin.site.register(User, UserAdmin)
admin.site.register(PhoneOTP)

admin.site.unregister(Group)

serializers.py
User = get_user_model()

class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('phone','password')
extra_kwargs = {"password":{'write_only': True}}

def create(self,validated_data):
user = User.objects.create(validated_data['phone'],None,validated_data['password'])
return user

class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id','phone']

class LoginSerializer(serializers.Serializer):
phone = serializers.CharField()
password = serializers.CharField(style= { 'input_type': 'password'},trim_whitespace=False)
def validate(self, data):
user = authenticate(**data)
if user.phone and user.password:
return user
raise serializers.ValidationError("Unable to log in with provided credentials.")


当我尝试使用 APIView 创建用户时,用户已创建,我也可以在 Django 管理员中看到该用户,但密码字段未散列,它说 Invalid password format or unknown hashing algorithm. 我在这里使用了自定义用户模型来使用电话号码作为用户名领域,但问题仍然存在。我使用的是当前版本的 Django,即 2.2,因此,我也无法登录该应用程序。

最佳答案

使用 set_password() 方法创建密码

或者

将 User.objects.create_user() 用于您的代码。

像这样编辑您的代码。

class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('phone','password')
extra_kwargs = {"password":{'write_only': True}}

def create(self,validated_data):
user = User.objects.create_user(validated_data['phone'],None,validated_data['password'])

return user

关于python - 如何在自定义用户模型 Django 中修复 "Invalid password format or unknown hashing algorithm.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56701988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com