【问题标题】:django clean_field not reading a form fielddjango clean_field 没有读取表单域
【发布时间】:2021-06-08 23:51:00
【问题描述】:

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

我创建了一个干净的函数,但是当我尝试引用字段“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 来使其工作。这种方法的问题在于,引发的错误消息出现在我所有表单的顶部,而不是实际表单的旁边。

【问题讨论】:

    标签: python python-3.x django django-forms


    【解决方案1】:

    要对多个字段运行验证,您应该重写 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
    

    【讨论】:

      猜你喜欢
      • 2013-02-26
      • 2015-01-23
      • 2021-11-17
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2014-08-22
      相关资源
      最近更新 更多