当我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')