1

我有一个管理员主详细信息,使用表格内联表单。

我有一些特殊的验证要完成:

  1. 如果“field_type”是“list”,则验证表单集中是否已添加至少一项。
  2. 但如果不是(field_type 有另一个值),则不要验证。

如果“field_type”是“list”,则使表单集可见,否则隐藏它。这是 javascript。我还必须在服务器上验证这一点。我在 ValueItemInlineFormSet 的 clean() 上执行此操作。问题是现在总是验证表单集,它应该只在 field_type = "list" 时发生。如何将主字段的值放入表单集中?

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']
4

0 回答 0