Django Validate Forms

0

I'm trying to make a form to store company information, so far it works perfectly when it saves to database etc.

I am using forms.Form the detail is that in a template I am not using {% forms.as_p%} if not each one separately in order to make it clearer and in an order, doing it for example {{form. name}} the detail is that I have no idea how to validate that the fields are full, in theory this has an if for is valid but I can not make it work.

def nuevo_ingreso(request):
    if request.method == "POST":
        form = Base_de_datos(request.POST)

        nombre = request.POST['nombre_persona'] 
        telefono = request.POST['telefono_persona']  


        if form.is_valid():
         Guarda!

I appreciate any help!

    
asked by Rodrigo Calderon 24.10.2016 в 04:14
source

1 answer

5

There are several ways to validate the fields of a form with django, according to what you need at the moment ... maybe the easiest is with the help of javascript and jquery

<script>
$(document).ready(function(){
    $('form').submit(function(event) { // o el id de tu formulario
        if($('#{{form.nombre.id_for_label}}').val() == '') {
            // aqui puedes hacer lo que quieras, como poner clases de error en tus inputs para especificar el error, lanzar un alert, como sea
            return false;
        }
    })

})
</script>

Another way is the validation by server, it would be when you define the form, I'll give you an example ...

forms.py

class Formulario(forms.Form):
    """
    Formulario de ejemplo
    """
    nombre = forms.CharField(max_length=255, label='nombre')

    def __init__(self, *args, **kwargs):
        super(Formulario, self).__init__(*args, **kwargs)
        # desde aqui, puedes definir luego de iniciar el formulario, si los campos son obligatorios
        self.fields['nombre'].required = True, # asi no entrara al save, si el campo no esta lleno

    # usar el metodo clean para otro tipo de validaciones
    def clean(self, *args, **kwargs):
        cleaned_data = super(Formulario, self).clean(*args, **kwargs)
        nombre = cleaned_data.get('nombre', None)
        if nombre is not None:
            if nombre == 'Maria':
                self.add_error('nombre', '"Maria" No es un nombre permitido')

Another recommendation, is that if you use a Django form, do not remove the variables by means of the request ie ... a correct way to validate the form in your views.py would be like this ...

views.py

def validar_formulario(request):
    if request.method == 'POST':
        form = Formulario(data=request.POST)
        if form.is_valid():
           nombre = form.cleaned_data('nombre')

IMPORTANT !!! ... if you use a form that inherits from the forms.Form class (as you put it in your example, and in which I put you ...) you can not use a form.save (), basically because it is not assigned to any model ...

I hope I have helped you friend ... Greetings and comment on any concerns or doubts: D

    
answered by 24.10.2016 в 16:32