Django: how to use forms.ValidationError and display messages in the template

1

I would like to inform the user (in the html template) of a message when identifying an existing email in the registration page. In forms.py I use the clean_email function to check if there is an email already registered.

After checking for an email already registered, I would like to see the following message: "The confirmation is not correct!". But it does not appear on the html page! What's wrong?

forms.py

class ClienteForm(forms.ModelForm):

cnpj = forms.CharField(
    label = "CNPJ", widget=forms.TextInput(),
    required = True)

email = forms.EmailField(label='E-mail', required = True)

def clean_email(self):
    email = self.cleaned_data['email']
    if Cliente.objects.filter(email=email).exists():
        print("Email já existe")
        raise forms.ValidationError('Email ja cadastrado!')
    return email


def save(self, commit = True):
    user = super(ClienteForm,self).save(commit =False)
    user.set_password(self.cleaned_data['password1']) #Quem autentica é User!
    user.username = Cliente.objects.count() + Contador.objects.count() + 1
    if commit:
        user.save()
    return user

class Meta:
    model = Cliente
    fields =  ['razao_social','celular','cnpj','telefone','email']

register.html

<form class="pure-form pure-form-stacked" method="post">
          {% csrf_token %}
          {{ formCliente.non_field_errors }}

         <div class="field-wrap">
            <label>
            Razão Social<span class="req">*</span>
            </label>
            {{ formCliente.razao_social }}
            {{ formCliente.razao_social.errors }}
          </div>

          <div class="field-wrap">

            <label>
            CNPJ<span class="req">*</span>
            </label>
            {{ formCliente.cnpj }}
            {{ formCliente.cnpj.errors }}
          </div>

          <div class="field-wrap">
            <label>
            Email<span class="req">*</span>
            </label>
            {{ formCliente.email }}
            <div>{{ formCliente.email.errors }}</div>

          </div>


          <div class="field-wrap">
            <label>
            Telefone
            </label>
            {{ formCliente.telefone }}
            {{ formCliente.telefone.errors }}
          </div>

          <div class="field-wrap">
            <label>
            Celular
            </label>
            {{ formCliente.celular }}
            {{ formCliente.celular.errors }}
          </div>



          <div class="field-wrap">
            <label>
            Senha<span class="req">*</span>
            </label>
            {{ formCliente.password1 }}
            {{ formCliente.password1.errors }}
          </div>


          <div class="field-wrap">
            <label>
            Confirme a senha<span class="req">*</span>
            </label>
            {{ formCliente.password2 }}
            {{ formCliente.password2.errors }}
          </div>

          <p class="forgot"><a href="{% url 'accounts:page_login' %}">Acessar sua conta?</a></p>

          <button type="submit" class="button button-block"/>Cadastrar</button>


      </form>

views.py

def register(request):
template_name = 'register.html'
if request.method == 'POST':
    clienteForm = ClienteForm(request.POST)
    if clienteForm.is_valid():
        cliente = clienteForm.save()


formCliente = ClienteForm()

context = {
    'formCliente':formCliente
}

return render(request, template_name, context)
    
asked by anonymous 26.06.2018 / 18:11

1 answer

1

The problem is in your view register in the views.py file. You are checking if the request method is POST , then try to validate the data by calling the is_valid method, the problem is whether it is valid or invalid does not make a difference because immediately below you are initializing another form but with another name variable, in the POST method the variable name is clienteForm , and in the method that would be GET the name is formCliente . And in the render function you pass as an argument the form formCliente which will always be an empty form, that is, without errors. Your view should look something like this:

def register(request):
    template_name = 'register.html'
    if request.method == 'POST':
        form = ClienteForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = ClienteForm()
    context = {
        'form': form
    }
    return render(request, template_name, context)

I hope I have helped.

    
15.07.2018 / 21:03