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