python

Encrypt a password field in Django models

If you are saving passwords in your application created using Python Django and want to encrypt passwords to secure them, you can use the make_password() method for that.

from django.contrib.auth.hashers import make_password

class Student(models.Model):
    s_name = models.CharField(max_length=50, null=False)
    s_password = models.CharField(max_length=30, null=False)

    def save(self, *args, **kwargs):
        self.s_password = make_password(self.s_password)
        super(Student, self).save(*args, **kwargs)

If we are using a password field in our Django models and want to encrypt the password while saving it to enhance the security, you can use the make_password() function that is imported from django.contrib.auth.hashers module.

from django.contrib.auth.hashers import make_password

In the code snippet, we have created a model named Student and created two fields inside it - s_name and s_password. We want to encrypt the password field s_password while saving it. To do that we have defined the save() function that will be called while saving values to the database. We have reassigned s_password by passing it to the make_password() function that will return the encrypted and secure value of the given password.

def save(self, *args, **kwargs):
    self.s_password = make_password(self.s_password)
    super(Student, self).save(*args, **kwargs)
from django.contrib.auth.hashers import make_password

password = 'PASSWORD_HERE'

s_form = StudentForm(commit=False)
s_form.password = make_password(password)
s_form.save()
In this code example, we are using the make_password() function to encrypt the password. We are saving the password from view here.
Was this helpful?