当我try 使用管理界面为用户创建密码时,它不会被散列. 所以我在用户模型中添加了这一行

    def save(self, *args, **kwargs):
        self.set_password(self.password)

虽然这解决了问题. 虽然创建用户使用createsuperuser它保存密码作为一个散列,但当我试图登录到管理界面是说不正确的密码. 我敢肯定这是由于在代码中添加了上面的一行而引起的. 当我删除这行时,gamesuperuser工作正常,但密码在管理界面中没有散列,当我添加行时,gamesuperuser工作,而gamesuperuser不工作. 如果密码尚未散列,我想散列.

class CustomUser(AbstractUser):
    role = models.ForeignKey(to=Role, to_field='role', on_delete=models.CASCADE, null=True, blank=True)
    username = models.CharField(max_length=100, unique=True, editable=True, validators=[MinLengthValidator(5)], null=False)
    image = models.ImageField(upload_to='profile_pics/', blank=True)
    password = models.CharField(max_length=128)
    complaint = GenericRelation(Complaint)
    # Specify unique related names for the groups and user_permissions fields
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name='custom_users',  # Change the related name to 'custom_users'
    )

    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('user permissions'),
        blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name='custom_users',  # Change the related name to 'custom_users'
    )

    def __str__(self):
        return f'{self.username}'

    def save(self, *args, **kwargs):
        if self.role_id == 'admin':
            self.is_staff = True

        if self.image:
            img = Image.open(self.image.path)

            if img.height > 300 or img.width > 300:
                output_size = (300, 300)
                img.thumbnail(output_size)
                img.save(self.image.path)
        super().save(*args, **kwargs)
@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
    list_display = ('username', 'password', 'image', 'role')

推荐答案

不要在.save(…)方法中散列:这将在每次你再次保存模型对象时散列密码.由于createsuperuser已经散列了密码,因此它将再次散列密码,使其对(第一个)密码无效.它需要使用第一个密码的哈希值登录.

Django的默认admin for User的工作方式是插入一个哈希表.我们也可以为自定义admin插入这个功能:

from django.contrib.auth.forms import UserChangeForm, UserCreationForm


class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'role', 'image')


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'role', 'image')


@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):
    list_display = ('username', 'password', 'image', 'role')
    form = CustomUserChangeForm
    add_form = CustomUserCreationForm

这也将确保密码显示为<input type="password'>,从而将密码隐藏在屏幕上.

Django相关问答推荐

如何在Django中显示文件大小

使用OuterRef过滤器获取Django记录的最大值

如何组织 Django REST Framework url

`.objects` 属性在哪里添加到 Django 的 models.Model 类中的实例命名空间?

Nginx 响应 404 not found on Django media URL in preprod, dev ok

如何在 ModelViewSet 逻辑中读取查询字符串值?

在 Django 中处理信用卡付款的最佳 Select 是什么?

相同的字符串不同的翻译

Django:如何在表单 clean() 方法的 django 验证错误中添加 超链接?

如何在 Django 中返回静态 HTML 文件作为响应?

Django中视图的多个decorator :执行顺序

超过 1 个外键

在 Django 中使用邮箱地址或用户名登录用户

获取 django 应用的绝对路径

如何重置 PostgreSQL 表上的 ID 序列

UpdateView 中的success_url,基于传递的值

在 Django 中的字段中添加额外的约束

为什么我的 Django 单元测试不知道安装了 MessageMiddleware?

使用 request.user 的 Django 和中间件始终是匿名的

Django 模型(1054,Unknown column in 'field list')