Validate end_date is bigger than start_date in Django Model Form
Asked Answered
F

3

9

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.

Florafloral answered 8/9, 2011 at 22:47 Comment(1)
Closed.... this answer my question... #2117548Florafloral
M
15

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.")
Mordy answered 9/9, 2011 at 1:41 Comment(2)
I get name 'cleaned_data' is not definedEnjoyment
cleaned_data = super().clean()Betweentimes
L
4

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.")
Links answered 16/5, 2019 at 7:57 Comment(0)
I
3

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
Industrial answered 7/10, 2014 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.