ValidationError while using ModelForm Django


I am very new to Django. I am working on a small project in which I am using ModelForm.
For the date field, I want to do custom validation i.e. whenever a user enters a date before today’s date it should display an error message near the date field. I have written code as per Django’s documentation, but it gives ValidationErrors for the raise statement in model form. like below:

ValidationError at /add_task/
[u"Please enter valid date. Either today's date or after that."]

Please help me how to overcome this problem. Thanks in advance.

from django.db import models

class MyTask(models.Model):
    def __unicode__(self):
        return self.summary

from django.forms import ModelForm, Textarea
from django.forms.extras.widgets import SelectDateWidget
from django.core.exceptions import ValidationError
from assignment.models import MyTask

import datetime

class AddTaskForm(ModelForm):

    class Meta:
        widgets = {
            'description': Textarea(attrs={'cols': 50, 'rows': 10}),
    def get_due_date(self):
        if diff.days<0:
            raise ValidationError("Please enter valid date. Either today's date or after that.")
            return self.cleaned_data['due_date']    
    def get_summary(self):
            return self.cleaned_data['summary']

    def get_description(self):
            return self.cleaned_data['description']

Asked By: Ravi Kant



Your validation method needs to be called clean_due_date. In Django < 3 it should raise forms.ValidationError, but in Django 3 it should use core.exceptions.ValidationError.

I have no idea what the get_summary and get_description methods are for, they aren’t called and don’t do anything useful.

See the Django 3 docs here and the Django 2 docs here.

Answered By: Daniel Roseman