Custom validation in Django Admin list view

In my previous post, I explained how to apply Custom validation in Django admin form. But we can also make one or more field editable in the list view. In this post I’m going to explain how to apply custom validation in list view.

We’ll just modify the CountryAdmin class described in the previous post.

file: admin.py

from django import forms
from myapp.models import Country
from django.contrib import admin
from functools import update_wrapper, partial
from django.forms.models import (modelform_factory, modelformset_factory,
                                 inlineformset_factory, BaseInlineFormSet)
 
class CountryForm(forms.ModelForm):
 
    class Meta:
        model = Country
 
    def clean_featured(self):
 
        featuredCount = Country.objects.filter(featured=True).count()
 
        if featuredCount >= 5 and self.cleaned_data['featured'] is True:
            raise forms.ValidationError("5 Countries can be featured at most!")
        return self.cleaned_data['featured']

class CountryAdmin(admin.ModelAdmin):

    form = CountryForm
    list_display = ('name', 'featured')
    list_editable = ('featured',)
 
    def get_changelist_formset(self, request, **kwargs):

        defaults = {
            "formfield_callback": partial(super(CountryAdmin, self).formfield_for_dbfield, request=request),
            "form": CountryForm,
        }
        defaults.update(kwargs)

        return modelformset_factory(Country,
                                    extra=0,
                                    fields=self.list_editable, **defaults)

    admin.site.register(Country, CountryAdmin)

So, basically we’ll need to over ride get_changelist_formset method to meet our need.

Leave a Reply