Django: how to use Forms.Validationerror and display messages in the template

Asked

Viewed 1,286 times

2

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

After checking the existence of an email already registered, I would like the following message to appear: "The confirmation is not correct!". But it doesn’t appear in 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>

py views.

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)

1 answer

2


The problem is in your view register in the archive views.py. You are checking whether the request method is POST, then tries to validate the data by calling the method is_valid the problem is if the same is valid or invalid makes no difference because right below you are starting another form but with another variable name, in the method POST the variable name is clienteForm, and in the method that would be the GET the name is formCliente. And in function render you pass as argument the form formCliente which will always be an empty form, ie 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’ve helped.

  • 1

    Thank you very much!!! It worked perfectly!

  • 1

    Glad to know. If you have any questions please do not hesitate to ask.

Browser other questions tagged

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