Search code examples
pythondjangoformsdjango-rest-frameworkdjango-forms

forms.ValidationError aren't being displayed on form


i'm trying to show an error message bellow the input on my register form, although it isn't being showed. On my tests the form is considered invalid by django on the if respostas_form.is_valid(): condition, but the message that was suposed to be displayed is not apearing. ( the name of variables and funcs of the codes are in portuguese cz i'm brazilian )

html:

{% for field in cadastro.visible_fields %}
    <div class="inputContainer">
      <label class="forms__label" for="{{field.id_for_label}}" class="inputText">{{field.label}}</label>
      {{field}}
      {% for error in field.errors %}
        <div class="alert alert-danger">
            {{error}}
        </div>
      {% endfor %}
  </div>
{% endfor %}

forms.py

class CadastroForm(forms.Form):
  email = forms.EmailField(
    max_length=100,
    required=True,
    label='Email',
    widget=forms.TextInput({
      "class": 'forms__input',
      "placeholder": "[email protected]",
    })
  )
  nome_de_usuario = forms.CharField(
    max_length=100,
    required=True,
    label="Nome de usuário",
    widget=forms.TextInput({
      "class": 'forms__input',
      "placeholder": "Ex.: Jóse Dávila",
    })
  )
  senha = forms.CharField(
    max_length=70,
    required=True,
    label="Senha",
    widget=forms.PasswordInput({
      "id": "userPasswordInput",
      "class": 'forms__input',
      "placeholder": "Exemplo1234+",
    })
  )
  senha2 = forms.CharField(
    max_length=70,
    required=True,
    label="Confirme sua senha",
    widget=forms.PasswordInput({
      "id": "userPasswordInput",
      "class": 'forms__input',
      "placeholder": "Exemplo1234+",
    })
  )


  def clean_senha2(self):
    senha = self.cleaned_data.get('senha')
    senha2 = self.cleaned_data.get('senha2')

    if senha and senha2:
        if senha != senha2:
            raise forms.ValidationError('Senhas não são iguais')
        else:
            return senha2

views.py

def cadastrar(request):

  if request.user.is_authenticated:
    return redirect('inicio')

  cadastro_form = forms.CadastroForm()

  if request.method == 'POST' and request.POST:
    respostas_form = forms.CadastroForm(request.POST)
    cadastro_result = cadastrar_usuario(request, respostas_form)
    if cadastro_result: return cadastro_result

  return render(request, 'usuarios/cadastrar.html', {
    "cadastro": cadastro_form,
  })

function cadastrar_usuario

def cadastrar_usuario(request, respostas_form:CadastroForm):
  if respostas_form.is_valid():

    nome = respostas_form['nome_de_usuario'].value()
    email = respostas_form['email'].value()
    # nascimento = respostas_form['nascimento'].value()
    senha = respostas_form['senha'].value()

    if User.objects.filter(email=email).exists():
      messages.error(request, " Já existe um usuário cadastrado com esse email!!")
      return redirect('cadastrar')

    if User.objects.filter(username=nome).exists():
      messages.error(request, " Já existe um usuário cadastrado com esse nome!!")
      return redirect('cadastrar')

    usuario = User.objects.create_user(password=senha, username=nome, email=email)
    usuario.save()

    messages.success(request, f"Olá {nome}, seu cadastro foi efetuado com sucesso!")
    return redirect('entrar')

I tryed to show a error message for the senha2 input field using the djangoss clean method, but it doesn't work


Solution

  • The problem is inside your view. Currently you are not rendering the ValidationError raised in forms because you have two different instances cadastro_form and respostas_form.

    The ValidationError is inside the latter. And, if your function result is False then cadastro_form is rendered again. You just need to render the correct form.

    views.py

    def cadastrar(request):
        if request.user.is_authenticated:
            return redirect('inicio')
    
        if request.method == 'POST' and request.POST:
            cadastro_form = forms.CadastroForm(request.POST)
            cadastrar_usuario(request, cadastro_form)
    
        else:
            cadastro_form = forms.CadastroForm()
    
        return render(request, 'usuarios/cadastrar.html', {
            "cadastro": cadastro_form,
        })