1

I have a start_date and end_date fields in save_related action of my Django Admin. 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. Here is what i have tried so far:

My django admin code:

@admin.register(models.Event)
class EventAdmin(admin.ModelAdmin):
...
    def save_related(self, request, form, formsets, change):
        obj = form.instance
        # Check validations
        start_date = obj.start
        end_date = obj.end
        if end_date < start_date:
            msg = u"End date should be greater than start date."
            self._errors["end_date"] = self.error_class([msg])
            return
         ...

But this code have this error: 'EventAdmin' object has no attribute 'error_class' How can I fix this?

NinjaDev
  • 1,228
  • 11
  • 21
  • Could you please include some code that you have tried so far? See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – mullac Aug 12 '19 at 01:13
  • I updated my questions with some codes. – NinjaDev Aug 12 '19 at 01:25
  • I have the same error, did you solve it? – oshingc Feb 07 '20 at 18:38
  • @oshingc I used ValidationError in `clean` function in `model.py` file, not admin.py. ``` from django.core.exceptions import ValidationError def clean(self): # Check validations if end_date < start_date: raise ValidationError({'end': ['End date should be greater than start date.']}) ``` Please refer these codes: - [linke](https://github.com/ninjadev999/google_calendar_events_manager/blob/334a2557fb817633528bcc212d99b86d222c88cb/events/models.py) – NinjaDev Feb 08 '20 at 19:35

1 Answers1

0
class CourseForm(forms.ModelForm): 

    def clean(self):
        cleaned_data = super(CourseForm, self).clean()
        start_date = self.cleaned_data.get('start_date')
        end_date = self.cleaned_data.get('end_date')
        if end_date < start_date:
            raise forms.ValidationError("End date should be greater than start date.")
        return cleaned_data

class CourseAdmin(admin.ModelAdmin):
    form = CourseForm
Jamin
  • 133
  • 12