Python Django如何在django models.py中创建哈希字段

时间:2018-08-04 05:01:21

标签: python django python-3.x django-models django-model-field

我正在研究一个Python(3.6)和Django(1.10)项目,我需要保存一些第三方服务的用户凭据,例如用户名,密码和电子邮件,我仅实现了rest API,所以根本没有 form.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)

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

请帮帮我!

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用标准的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)