Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate end_date is bigger than start_date in Django Model Form

I have a start_date and end_date fields in my model, I want to assign an error to end_date when it is bigger than start_date, I have been looking docs, but don't find an example about that.

like image 291
juanefren Avatar asked Sep 08 '11 22:09

juanefren


3 Answers

You need a custom clean function in your form that does the check:

def clean(self):
    cleaned_data = super().clean()
    start_date = cleaned_data.get("start_date")
    end_date = cleaned_data.get("end_date")
    if end_date < start_date:
        raise forms.ValidationError("End date should be greater than start date.")
like image 176
Rob Osborne Avatar answered Oct 25 '22 18:10

Rob Osborne


This is an update for Django 2.2 - doc

from django import forms
from .models import Project

class ProjectAddForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = [
            'name', 
            'overview',
            'start_date',
            'end_date',
            'status',
            'completed_on',
        ]

        labels = {
            "name": "Project Name",
            "overview": "Project Overview",
            "status": "Project Status",
        }

    # Logic for raising error if end_date < start_date
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get("start_date")
        end_date = cleaned_data.get("end_date")
        if end_date < start_date:
            raise forms.ValidationError("End date should be greater than start date.")
like image 23
Cipher Avatar answered Oct 25 '22 18:10

Cipher


This is the actual recommended example from the docs

In short, remember to return cleaned_data, and raise form errors correctly.

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "[email protected]" not in data:
            raise forms.ValidationError("You have forgotten about Fred!")

    # Always return the cleaned data, whether you have changed it or
    # not.
    return data
like image 31
rix Avatar answered Oct 25 '22 19:10

rix