Django how to prevent to accept future date?

Question:

I added this validation in my froms.py for prevent to accept future date. But I am not undersating why it’s not working and forms still now submitting with future date. here is my code:

import datetime
 
class AddPatientFrom(forms.ModelForm):
         
         date_of_birth =  forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control','type':'date'}),required=True)
       
         class Meta:
             model = Patient
             fields = ['date_of_birth']
         
         def clean_date(self):
                date = self.cleaned_data['date_of_birth']
                if date < datetime.date.today():
                    raise forms.ValidationError("The date cannot be in the past!")
                return date   

I also want to know how to disable to pick future date from Django default html calendar?

Asked By: boyenec

||

Answers:

You are checking the opposite: it will rase an error if the date of birth is before today. You should check if the date of birth is after today when raising a validation error, so:

def clean_date_of_birth(self):
    date = self.cleaned_data['date_of_birth']
    if date > datetime.date.today():  # 🖘 raise error if greater than
        raise forms.ValidationError("The date cannot be in the future!")
    return date
Answered By: Willem Van Onsem

Your validation logic only raises error for past dates, not future dates.

Moreover, to validate date_of_birth field you need to implement clean_date_of_birth method.

From Form and field validation docs.

The clean_<fieldname>() method is called on a form subclass – where <fieldname> is replaced with the name of the form field attribute. This method does any cleaning that is specific to that particular attribute, unrelated to the type of field that it is…

Answered By: narendra-choudhary
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.