Django: how to make the clean function work

Viewed 74

I have a function to validate that the date field is not less than today's date but it does not work, when I send the data through the form the function does nothing.

forms.py

class CrearTareaForm(forms.ModelForm):
    descripcion = forms.CharField(max_length=500, required=True, widget=forms.TextInput(attrs={'placeholder':'Ingrese Descripcion'}))
    inicio = forms.DateTimeField(
        input_formats= ['%Y-%m-%dT%H:%M'],
        required=True,
        widget=forms.DateTimeInput(
            attrs={
                'type': 'datetime-local',
                'class': 'form-control'
            }
        ))

    def clean_inicio(self):
        inicio = self.cleaned_data['inicio']
        if inicio < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return inicio

views.py

def creartarea(request):
    data = {
        'tarea': CrearTareaForm()
    }
    if request.method=="POST":
        if request.POST.get('nombre') and request.POST.get('descripcion') and request.POST.get('inicio') and request.POST.get('termino') and request.POST.get('repetible') and request.POST.get('activo') and request.POST.get('estado') and request.POST.get('creador') and request.POST.get('tarea_anterior'):
            tareasave= Tarea()
            tareasave.nombre=request.POST.get('nombre')
            tareasave.descripcion=request.POST.get('descripcion')
            tareasave.inicio=request.POST.get('inicio')
            tareasave.termino=request.POST.get('termino')
            tareasave.repetible=request.POST.get('repetible')
            tareasave.activo=request.POST.get('activo')
            tareasave.estado=EstadoTarea.objects.get(pk=(request.POST.get('estado')))
            tareasave.creador=Empleado.objects.get(rut=(request.POST.get('creador')))
            tareasave.tarea_anterior=Tarea(pk=(request.POST.get('tarea_anterior')))
            cursor=connection.cursor()
            cursor.execute("call SP_crear_tarea('"+tareasave.nombre+"','"+tareasave.descripcion+"', '"+tareasave.inicio+"', '"+tareasave.termino+"', '"+tareasave.repetible+"', '"+tareasave.activo+"', '"+str(tareasave.estado.id)+"', '"+str(tareasave.creador.rut)+"', '"+str(tareasave.tarea_anterior.id)+"')")
            messages.success(request, "La tarea "+tareasave.nombre+" se guardo correctamente ")
            return render(request, 'app/creartarea.html', data)
    else:
        return render(request, 'app/creartarea.html', data)
1 Answers

You should define the clean_inicio method inside the ModelForm, also inicio is a DateTimeField so you should first extract it's date then compare it with current date, so:

class CrearTareaForm(forms.ModelForm):
    descripcion = forms.CharField(max_length=500, required=True, widget=forms.TextInput(attrs={'placeholder':'Ingrese Descripcion'}))
    inicio = forms.DateTimeField(
    input_formats= ['%Y-%m-%dT%H:%M'],
    required=True,
    widget=forms.DateTimeInput(
        attrs={
            'type': 'datetime-local',
            'class': 'form-control'
        }
    ))

    def clean_inicio(self):
        inicio = self.cleaned_data['inicio']
        if inicio.date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return inicio
Related