首页 > 解决方案 > django clean_field 没有读取表单域

问题描述

我希望我的代码在以下情况下引发错误:用户选择的角色==“其他”并且他们将“其他角色”字段留空。

我做了一个干净的函数,但是当我尝试引用字段“other_role”时,它总是显示为 None,即使在填写表格时也是如此。

如何引用另一个字段?

PS:我不想在我的表单类中再次明确定义该字段,因为这会打乱我的表单呈现的顺序。

class AttendeeForm(forms.ModelForm):
    # birth_date = forms.DateField(widget=forms.TextInput(attrs={
    #    'class':'datepicker'
    #}))
    class Meta:
        model = Attendee
        fields= ('birth_date', 'degrees','area_of_study','role','other_role','institute', 'phone_number')
        widgets = {
            'birth_date': DateInput()
        }
        help_texts = {
            'degrees': 'List your degrees. Separate with commas.',
            'area_of_study': 'List your primary field of study or research. If neither are applicable, write your area of practice.',
            'institute': 'Professional Affiliation. If retired, enter your most recent affiliation.'
        }

    def clean_role(self):
        cd = self.cleaned_data
        print(cd.get("other_role"))
        if cd['role'] == 'OTHER':
            if cd.get("other_role") is not False:
                raise forms.ValidationError("You need to specify your role if you picked 'Other'")
        return cd['role']

更新

通过将函数名称更改为 clean() 并返回 self.cleaned_data,我几乎可以让它工作。这种方法的问题在于,引发的错误消息出现在我所有表单的顶部,而不是实际表单旁边。

标签: pythonpython-3.xdjangodjango-forms

解决方案


要对多个字段运行验证,您应该覆盖该clean()方法

要将错误分配给特定字段,您可以将字典传递给ValidationError键是字段名称的位置:

class AttendeeForm(forms.ModelForm):
    ...

    def clean(self):
        cleaned_data = super().clean()
        role = cleaned_data.get('role')
        other_role = cleaned_data.get('other_role')
        if role == 'OTHER' and not other_role:
            raise ValidationError({'other_role': 'You need to specify your role if you picked "Other"'})
        return cleaned_data

推荐阅读