5

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!

1 Answer 1

10

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)
Sign up to request clarification or add additional context in comments.

8 Comments

What kind of salt can I generally use?
and Do I need to call make_password() method for all fields need to hashed like email & username ?
@AbdulRehman if you need this fields to be hashed then yes. As for salt you can actually not provided it to make_password method. In this case Django generate it automatically.
you can verify using check_password() function imported from django.contrib.auth.hashers module. You don't have to use any salt here if you haven't passed any salt at the make_password() django will use it's salt automatically.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.