7

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)
Sahana Prabhakar
  • 581
  • 1
  • 8
  • 21

4 Answers4

9

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()
Exprator
  • 26,992
  • 6
  • 47
  • 59
4

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
)
Samantha
  • 41
  • 2
  • Just a small modification: def save(self, *args, **kwargs): if not self.pk: self.write_key = make_password(self.write_key) – svebert Jun 12 '22 at 18:47
1

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()
Raja Simon
  • 10,126
  • 5
  • 43
  • 74
0

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