Django validate Cpf and treat error

Asked

Viewed 1,765 times

3

I’m using Brcpffield from the localflavors package to validate the CPF in a form, it’s working, the problem is that in the template when I type in an invalid CPF that Django error page appears, I just wanted a message to be displayed and the person could change the field again... What’s the best way to do it?

# form:

class ClienteForm(forms.ModelForm):

    cpf = BRCPFField()

    class Meta:
        model = Cliente
        fields = ('nome', 'cpf', 'celular', 'tel_fixo', 'email', 'end', 'data_cadastro')

# view:

def cadastrar_cliente(request):
    if request.method == 'POST':
        form = ClienteForm(request.POST)
        if form.is_valid():
            cliente = form.save()
            cliente.save()
            return redirect('/calcados/', {})
    else:
        form = ClienteForm()
        return render(request, 'calcados/cadastrar.html', {'form': form})

# template:

{% extends 'calcados/base.html' %}

{% block content %}
<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Salvar</button>
</form>
{% endblock%}

1 answer

2


We’re missing one else to load the page again with the form if there is an error:

def cadastrar_cliente(request):
    if request.method == 'POST':
        form = ClienteForm(request.POST)
        if form.is_valid():
            cliente = form.save()
            cliente.save()
            return redirect('/calcados/', {})
        else:
            # caso o formulario tenha erro:
            return render(request, 'calcados/cadastrar.html', {'form': form})
    else:
        form = ClienteForm()
        return render(request, 'calcados/cadastrar.html', {'form': form})

You could still do it like this:

def cadastrar_cliente(request):
    form = ClienteForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save()                
            return redirect('/calcados/', {})     
    # retorna a pagina com form vazio ou com erros:       
    return render(request, 'calcados/cadastrar.html', {'form': form})
  • 1

    worked out, thanks :)

  • You are welcome. If you feel that the answer has answered your question, you can accept it as an answer by marking beside :)

Browser other questions tagged

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