如何在列表显示表单上添加自定义验证 [英] How to add custom validation on a list display form
问题描述
我有一个模型,其中的a是用于设置元素是否处于活动状态的选项。
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.
我已经在AdminModel上编写了验证代码。因此,现在如果在编辑元素时将其标记为活动,并且达到 actvie元素的限制,则会引发异常。
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.
在管理界面中,我还有一个对象列表。
在此列表中,我已将字段活动标记为可编辑,
list_display =('name','first_promotion','second_promotion','active')
readonly_fields = ['name ']
list_editable = ['active']
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.
推荐答案
好问题!更改列表表单似乎是从 ModelAdmin.get_changelist_form
中提取的,您可以在其中提供自己的 ModelForm
作为modelformset的基础
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
如果要修改表单集验证(表单的集合) ),您将从django.forms.models import中覆盖 get_changelist_formset
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)
这篇关于如何在列表显示表单上添加自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!