How to add custom validation on a list display for

2020-07-18 07:54发布

I have a model in which the is an option for setting if an element is active or not.

There is restriction to the number of elements that can have the "active" property with a "True" value.

I have writen validation code on the AdminModel. So now if when editing an elemnt i mark it as "active" and i have reach the limit of "actvie" elements, i raise an exception.

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

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

What I want is to be able of also making this validation on the "list display" of the model. I'm not able where i should add the validation code for the list display.

Could anybody show me how to do this? Thanks in advance.

1条回答
▲ chillily
2楼-- · 2020-07-18 08:00

Good question! The changelist form appears to be pulled from ModelAdmin.get_changelist_form where you can supply your own ModelForm to serve as the modelformset base 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 modify the formsets validation (the collection of forms) you'd 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)
查看更多
登录 后发表回答