[Fixed]-Why Django return form is invalid?

1👍

the following fields are required:

  • usuario
  • nombres
  • direccion
  • apellidos
  • id_tipo_cliente
  • correo_electronico
  • telefono
  • telefono_celular

Add a required=False on them like you have on the password field, and you’ll be on your way.

You add an instance for the object, and that object has values for all the required form fields, so when you load form.as_p, or any other tag that outputs the entire form, it loads with all the required fields filled out. That way, when the form is submitted, there are no validation errors. Validity checks are done over request.POST and not on the original model instance, so when the form is submitted without some of the required fields, you get validation errors.

To debug these sorts of issues, add a {{form.errors}} somewhere in your template. That’s how I found the errors in your form.

It’s considered best practice to display all non-field related errors in a list at the top of the form and field-related errors next to each form field.
So you’d add something like this at the top of the template:

<ol>
  {% for error in form.non_field_errors %}
    <li><strong>{{ error|escape }}</strong></li>
  {% endfor %}
</ol>

And something like this for the image_cliente form field:

{% if form.image_cliente.errors %}
  <ol>
    {% for error in form.image_cliente.errors %}
      <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
  </ol>
{% endif %}

Leave a comment