6
votes

I have a model with name, code and password. I need to encrypt the password. Also I should'nt show a plain text in the password field. I referred to this link

Password field in Django model

But the answer is old and need to know what the present approach is.

My model is as below

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
4

4 Answers

9
votes

in your view

from django.contrib.auth.hashers import make_password
crew_password = 'take the input if you are using form'
form = FormName(commit=False)
form.crew_password=make_password(crew_password)
form.save()
3
votes

Add this to your model:

def save(self, *args, **kwargs):
    self.crew_password = make_password(self.crew_password)
    super(Crew, self).save(*args, **kwargs)

And to hide the text in the password field, in your form:

password = forms.CharField(
    widget=forms.PasswordInput
)
1
votes

Django added PasswordInput widget use that to make password field in your template

from django.forms import ModelForm, PasswordInput

class CrewForm(ModelForm):
    class Meta:
        model = Crew
        fields = '__all__'
        widgets = {
            'crew_password': PasswordInput(),
        }

Also as @Exprator suggest to use the make_password to update the password field in view...

form.crew_password=make_password(crew_password)
form.save()
0
votes

I've tried this method of making.

Add this is your model

from django.contrib.auth.hashers import make_password

  class Crew(models.Model):
    
        crew_id = models.AutoField(primary_key=True)
        crew_code = models.CharField(max_length=200, null=False, unique=True)
        crew_name = models.CharField(max_length=200, null=False)
        crew_password = models.CharField(max_length=200, null=False)

    def save(self, *args, **kwargs):
        self.password = make_password(self.password)
        super(Crew, self).save(*args, **kwargs)

This working for me .

Thanks