Field handling in the Model before writing to the database (Python + Django)

2

I am trying to perform a password encryption using Python 3.7 and Django 2.1.

Looking at the Python documentation, Django and some answers here in StackOverflow, I came up with the code as follows, however, the password field is written blank in the database.

This is a web form for user registration and before doing the recording in the database, I would like to perform some treatments on the password entered by the user.

Would anyone have any tips, documentation, etc. that could help fix this problem?

Here are the codes:

models.py

    from django.db import models

    class Usuario(models.Model):
            nome = models.CharField(max_length = 30)
            sobrenome = models.CharField(max_length = 30)
            email = models.EmailField(unique = True)
            usuario = models.CharField(max_length = 30, unique = True)
            _senha = models.CharField(max_length = 254, db_column = 'senha')
            criacao = models.DateTimeField(auto_now = False, auto_now_add = True)
            ativo = models.BooleanField(default = False)

    @property
    def senha(self):
            return self._senha

    @senha.setter
    def senha(self, value):
            self._senha = value

views.py

    from django.views.generic import CreateView

    from .models import Usuario
    from .forms import CadastrarUsuario

    class IndexView(CreateView):
            template_name = 'cadastro/index.html'
            model = Usuario
            form_class = CadastrarUsuario
            success_url = '/cadastro'

    def form_valid(self, form):
            form.send_email()
            return super().form_valid(form)

forms.py

    from django import forms

    from .models import Usuario

    class CadastrarUsuario(forms.ModelForm):

            nome = forms.CharField(widget = forms.TextInput(attrs = {'class': 'input_field'}),label = 'Nome')
            sobrenome = forms.CharField(widget = forms.TextInput(attrs = {'class': 'input_field'}), label = 'Sobrenome')
            email = forms.CharField(widget = forms.TextInput(attrs = {'class': 'input_field'}), label = 'E-mail')
            confirma_email = forms.CharField(widget = forms.TextInput(attrs = {'class': 'input_field'}), label = 'Confirmar E-mail')
            usuario = forms.CharField(widget = forms.TextInput(attrs = {'class': 'input_field'}), label = 'Login')
            senha = forms.CharField(widget = forms.PasswordInput(attrs = {'class': 'input_field'}), label = 'Senha')
            confirma_senha = forms.CharField(widget = forms.PasswordInput(attrs = {'class': 'input_field'}), label = 'Confirmar senha')

    class Meta:
            model = Usuario
            fields = ['nome', 'sobrenome', 'email', 'confirma_email', 'usuario', 'senha', 'confirma_senha']

    def clean(self):
            cleaned_data = super().clean()

            senha = cleaned_data.get('senha')
            confirma_senha = cleaned_data.get('confirma_senha')

            email = cleaned_data.get('email')
            confirma_email = cleaned_data['confirma_email']

            if senha != confirma_senha:
                    raise forms.ValidationError('Senha não confere! Digite a mesma senha nos campos Senha e Confirmar Senha.')

            if email and confirma_email:
                    if email != confirma_email:
                            raise forms.ValidationError('E-Mail não confere! Digite o mesmo e-mail nos campos E-mail e Confirma E-mail')

            return cleaned_data
    
asked by anonymous 31.08.2018 / 13:46

1 answer

1

I use django.contrib.auth.hashers to handle passwords. Basically you can use the make_password and check_password method to work with encryption.

Example:

from django.contrib.auth.hashers import make_password, check_password

senha_criada_pelo_usuario = '123abc'
senha_criptografada = make_password(password=senha_criada_pelo_usuario, salt=None, hasher='pbkdf2_sha256')

# para verificar se a senha corresponde a criptografada:
senha_informada_no_login = '123abc'
corresponde = check_password(password=senha_informada_no_login, encoded=senha_criptografada)
if corresponde:
    # <seu codigo>
    pass
    
31.08.2018 / 17:55