Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django validate one model field against another in admin

Say a model has two DateTimeFields:

class Tourney(models.Model):
    registration_deadline = models.DateTimeField()
    start_date = models.DateTimeField()

When a user tries to submit a Tourney from within the Django admin, how can I test that registration_deadline is before start_date before saving to the database and, if there is an error, of course inform the user inline, just as Django would if there were any OTHER validation errors?

Basically, I'm looking for custom admin validation.This part of the Django docs is close, but seems to be for forms. How can I do the 'Cleaning and validating fields that depend on each other' from within Django's admin? Even just a pointer to the right place in the docs would be sufficient.

Edit: I'm thinking it has something to do with validators, but they seem only able to test a single value, not two at the same time...

like image 804
fildred13 Avatar asked Mar 20 '23 12:03

fildred13


1 Answers

from django import forms
from django.contrib import admin

from .models import Tourney


class TourneyAdminForm(forms.ModelForm):
    class Meta:
        model = Tourney
        fields = '__all__'

    def clean(self):
        if self.cleaned_data['registration_deadline'] > self.cleaned_data['start_date']:
            raise forms.ValidationError('Registration deadline must be before the start date')
        return self.cleaned_data


class TourneyAdmin(admin.ModelAdmin):
    form = TourneyAdminForm


admin.site.register(Tourney, TourneyAdmin)
like image 170
crash843 Avatar answered Mar 24 '23 01:03

crash843