Search code examples
pythondjangopython-3.xdjango-modelsdjango-model-field

Python Django How to Create Hash Fields inside django models.py


I'm working on a Python(3.6) & Django(1.10) project in which I need to save some user credentials of the third party services like username, password, and email, I'm implementing only rest API, so there's no form.py at all. So, How can I make hash fields inside models.py file?

Here's my current 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)

I want to add three new hash fields like username, password & email.

Help me, please!

Thanks in advance!


Solution

  • You can use standard CharField. To store hash value use make_password method before saving:

    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)