5

我正在开发一个 Python(3.6) 和 Django(1.10) 项目,在该项目中我需要保存一些第三方服务的用户凭据,如用户名、密码和电子邮件,我只实现了 rest API,所以没有表单.py。那么,如何在models.py文件中创建哈希字段?

这是我当前的models.py

class DeploymentOnUserModel(models.Model):
    deployment_name = models.CharField(max_length=256, )
    credentials = models.TextField(blank=False)
    project_name = models.CharField(max_length=150, blank=False)
    project_id = models.CharField(max_length=150, blank=True)
    cluster_name = models.CharField(max_length=256, blank=False)
    zone_region = models.CharField(max_length=150, blank=False)
    services = models.CharField(max_length=150, choices=services)
    configuration = models.TextField(blank=False)
    routing = models.TextField(blank=True)

    def save(self, **kwargs):
        if not self.id and self.services == 'Multiple' and not self.routing:
            raise ValidationError("You must have to provide routing for multiple services deployment.")
        super().save(**kwargs)

我想添加三个新的哈希字段,如用户名密码电子邮件

请帮帮我!

提前致谢!

4

1 回答 1

9

您可以使用标准CharField. 保存前存储哈希值使用make_password方法:

from django.contrib.auth.hashers import make_password

password = models.CharField(max_length=256)

def save(self, **kwargs):
    some_salt = 'some_salt' 
    password = make_password(self.password, some_salt)
    if not self.id and self.services == 'Multiple' and not self.routing:
        raise ValidationError("You must have to provide routing for multiple services deployment.")
    super().save(**kwargs)
于 2018-08-04T05:10:32.723 回答