0

我使用 abstractuser 创建了一个自定义用户模型,并用用户名替换了 mobile,然后在 admin 中重新创建用户页面,但我的问题是我没有更改密码表单(在默认 Django 身份验证中),如果我把保存方法和更改其他数据在用户模型,然后存储空密码,用户无法再登录

模型.py:

class MyUser(AbstractUser):

    username = None
    mobile = models.CharField(max_length=15, unique=True)
    international_id = models.CharField(max_length=25, blank=True, null=True)
    company_name = models.CharField(max_length=255, blank=True, null=True)
    business_code = models.CharField(max_length=25, blank=True, null=True)
    otp = models.PositiveIntegerField(blank=True, null=True)
    otp_create_time = models.DateTimeField(auto_now=True)

    objects = MyUserManager()

    USERNAME_FIELD = 'mobile'
    REQUIRED_FIELDS = []

    backend = 'custom_login.mybackend.ModelBackend'

管理员.py:

class MyUserAdmin(admin.ModelAdmin):
    list_display = ['mobile','company_name']

    search_fields = ['mobile']

    form = UserAdminChangeForm
    fieldsets = (
            (None, {'fields': ('mobile','email','password','otp')}),
            ('Personal Info', {'fields': ('first_name', 'last_name','international_id')}),
            ('Company Info', {'fields': ('company_name','business_code')}),
            (_('Permissions'), {'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions')}),
            (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

    class Meta:
        model = MyUser
admin.site.register(MyUser,MyUserAdmin)

表格.py:

from django import forms
from .models import MyUser
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import ugettext as _

class UserAdminChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    # password = ReadOnlyPasswordHashField(label=("Password"),
    #     help_text=("Raw passwords are not stored, so there is no way to see "
    #                 "this user's password, but you can change the password "
    #                 "using <a href=\"../password/\">this form</a>."))

    password = forms.CharField(widget=forms.PasswordInput(),label=_('Password'), required=False)

    class Meta:
        model = MyUser
        fields = ['mobile', 'password', 'otp']

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

我需要单独一个页面来更改密码,或者我需要一些代码,当我输入空密码时它不会更改密码,因为当我填写空白密码并编辑用户然后密码存储为空并且用户无法再登录...例如,我更改了用户的名字,然后在该用户无法登录后按保存按钮(密码字段为空白),因为为该用户存储了空密码

4

0 回答 0