Django 未对密码进行哈希处理的自定义用户

huangapple go评论64阅读模式
英文:

django not hashing password custom user

问题

我正在处理一个继承自django.contrib.auth.models的模型,名为AbstractBaseUser

之前,我是这样指定password字段的:

password = models.CharField(max_length=150)

但后来我需要将其指定为:

create_password = models.CharField(max_length=150)

在之前的情况下,我得到的密码是以哈希格式存储的。但在将password更改为create_password后,该值以未经哈希处理的格式(原始输入值)保存。

除此之外,所有其他设置与以前相同,我使用user.set_password(create_password)函数,但仍然没有哈希。

如何对create_password字段进行哈希处理?

英文:

i am working on a model which inherits from from django.contrib.auth.models import AbstractBaseUser

earlier i was specifying password field like:

password = models.Charfield(max_length=150)

but then i need to specify it as:

create_password = models.CharField(max_length=150)

in earlier case i was getting password in hashed format.
but after changing password to create_password
the value is saving in unhashed format (originally entered value).

all other settings are same as before, i am using user.set_password(create_password) function . but still no hashing.

how can i hash create_password field?

答案1

得分: 0

以下是翻译好的部分:

Django中AbstractBaseUser中的设置密码功能期望密码字段名称只能是'password',如果您打开AbstractBaseUser类,该功能如下:

def set_password(self, raw_password):
    self.password = make_password(raw_password)
    self._password = raw_password

但如果出于某种原因,您需要将密码字段命名为'create_password'而不是'password',您可以在用户模型中像这样覆盖'set_password'函数:

def set_password(self, raw_password):
    self.create_password = make_password(raw_password)
    self._password = raw_password

我假设您已在settings.py文件中设置了用户模型,并创建了Manager类。

英文:

The set password function in Django AbstractBaseUser expects the password field name to be 'password' only, this is how the function looks if you go inside the AbstractBaseUser class:

def set_password(self, raw_password):
    self.password = make_password(raw_password)
    self._password = raw_password

But if you for some reason need your password field to be create_password instead of 'password' you can override the 'set_password' function in your user model like this:

def set_password(self, raw_password):
    self.create_password = make_password(raw_password)
    self._password = raw_password

I am assuming you have set your user model in the settings.py file and have created the Manager class as well.

huangapple
  • 本文由 发表于 2023年2月18日 16:53:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定