我有一个管理主信息,使用表格内联表格。
我有一些特殊的验证要做:
如果“field_type”是“list”,那么,使formset可见,否则隐藏它。这是javascript。我还必须在服务器上验证它。我在ValueItemInlineFormSet的clean()上执行此操作。问题是现在总是验证formset,它应该只在field_type =“list”时发生。如何将我的主字段的值放入formset?
class ValueItemInlineFormSet(BaseInlineFormSet):
def clean(self):
"""Check that at least one service has been entered."""
super(ValueItemInlineFormSet, self).clean()
if any(self.errors):
return
print(self.cleaned_data)
if not any(cleaned_data and not cleaned_data.get('DELETE', False) for cleaned_data in self.cleaned_data):
raise forms.ValidationError('At least one item required.')
class ValueItemInline(admin.TabularInline):
model = ValueItem
formset = ValueItemInlineFormSet
class MySelect(forms.Select):
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
data_attrs = self.attrs['data_attrs']
option_attrs = ''
if data_attrs and option_value:
obj = self.choices.queryset.get(id=option_value)
for attr in data_attrs:
attr_value = getattr(obj, attr)
option_attrs += 'data-{}={} '.format(attr, attr_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
return format_html('<option value="{}" {}{}>{}</option>', option_value, option_attrs, selected_html, force_text(option_label))
class RequirementFieldForm(forms.ModelForm):
field_type = forms.ModelChoiceField(queryset=FieldType.objects.all(),
widget=MySelect(attrs={'data_attrs': ('identifier', 'name')}))
def __init__(self, *args, **kwargs):
self.qs = FieldType.objects.all()
super(RequirementFieldForm, self).__init__(*args, **kwargs)
class Meta:
model = RequirementField
fields = ['field_type', 'name', 'description', 'identifier', 'mandatory', 'order_nr', 'active']