django 保存自定义用户密码
时间: 2023-11-16 21:04:32 浏览: 35
在 Django 中,可以使用 Django 自带的 `make_password` 函数来对用户密码进行加密,也可以使用自定义的加密方式。
使用 Django 自带的加密方式:
```python
from django.contrib.auth.hashers import make_password
password = 'my_password'
hashed_password = make_password(password)
```
使用自定义的加密方式:
```python
import hashlib
password = 'my_password'
hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
```
将加密后的密码保存到用户模型中:
```python
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email))
user.password = make_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email=email, password=password)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(unique=True)
password = models.CharField(max_length=128)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = MyUserManager()
USERNAME_FIELD = 'email'
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.is_admin
```
在上面的示例中,我们使用 `make_password` 函数将密码加密后保存到了用户模型中的 `password` 字段中。如果你使用的是自定义的加密方式,需要将加密后的密码保存到 `password` 字段中。