ValidationError while using ModelForm Django

Question:

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.

models.py

from django.db import models

class MyTask(models.Model):
    summary=models.CharField(max_length=100)
    description=models.CharField(max_length=500)
    due_date=models.DateField(null=True)
    completed_status=models.BooleanField()
    
    def __unicode__(self):
        return self.summary

forms.py

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:
        model=MyTask
        fields=('summary','description','due_date')
        widgets = {
            'description': Textarea(attrs={'cols': 50, 'rows': 10}),
            'due_date':SelectDateWidget(),
        }
        
    def get_due_date(self):
        diff=self.cleaned_data['due_date']-datetime.date.today()
        if diff.days<0:
            raise ValidationError("Please enter valid date. Either today's date or after that.")
        else:
            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

||

Answers:

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