Model field processing before writing to the database (Python + Django)

Asked

Viewed 700 times

2

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

Looking at the documentation of Python, Django and some answers here in Stackoverflow, I arrived at the code as follows, however, the password field is written blank in the database.

This is a web form of user registration and before performing the recording in the database, I would like to perform some processing in the password informed by the user.

Would anyone have any tips, documentation, etc that might help in fixing this problem?

Follow below the codes:

py.models

    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

py views.

    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

1 answer

1


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

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
  • 1

    Thanks Paulo, it didn’t turn out exactly as I expected! But anyway your tip solved the problem. Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.