How to add custom validation in a list display form

I have a model in which there is an option to install if the item is active or not.

There is a limit on the number of elements that can have an โ€œactiveโ€ property with a โ€œtrueโ€ value.

I have an authentication code in AdminModel. So now, if when editing an element I mark it as โ€œactiveโ€ and I have reached the limit of the โ€œactvieโ€ elements, I am throwing an exception.

def clean_active(self): if self.cleaned_data["active"]: #check number of active elements in model. 

In admin interface, I also have a list of objects. In this list I have been marked as an editable field "active", list_display = ('name', 'first_promotion', 'second_promotion', 'active') readonly_fields = ['name'] list_editable = ['active']

What I want is also the ability to do this check on the "list display" of the model. I cannot, where should I add a verification code to display a list.

Can someone show me how to do this? Thanks in advance.

+4
source share
1 answer

Good question! The change list form is derived from ModelAdmin.get_changelist_form , where you can provide your own ModelForm , which will serve as the base modelformset model.

 class MyForm(forms.ModelForm): def clean_active(self): cd = self.cleaned_data.get('active') limit = 5 # replace with logic if cd >= limit: raise forms.ValidationError("Reached limit") return cd class Meta: model = MyModel class MyModelAdmin(admin.ModelAdmin): def get_changelist_form(self, request, **kwargs): return MyForm 

If you want to change form validation (form set), you override get_changelist_formset

 from django.forms.models import BaseModelFormSet class BaseFormSet(BaseModelFormSet): def clean(self): print self.cleaned_data # this is the cleaned data for ALL forms. if 'your_condition': raise forms.ValidationError("Your error") return self.cleaned_data class MyModelAdmin(admin.ModelAdmin): def get_changelist_formset(self, request, **kwargs): kwargs['formset'] = BaseFormSet return super(MyModelAdmin, self).get_changelist_formset(request, **kwargs) 
+5
source

Source: https://habr.com/ru/post/1392371/


All Articles