django validate cpf and treat error

2

I'm using the BRCPFField of the localflavors package to validate the CPF in a form, it's working, the problem is that in the template when I type 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 is the best way to do this?

# 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%}
    
asked by anonymous 19.06.2015 / 16:55

1 answer

0

You are missing a 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})
    
19.06.2015 / 17:04