python - 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,我几乎可以让它工作。这种方法的问题在于,引发的错误消息出现在我所有表单的顶部,而不是实际表单旁边。
解决方案
要对多个字段运行验证,您应该覆盖该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
推荐阅读
- python - 有没有办法每 X 秒/分钟重新加载一次 API
- python-3.x - 如何在 Python 底图上绘制值?
- python - FlaskApp 没有属性“配置”
- python - 在最后一个 for 循环中,当满足 Y=0 时,我将排除循环的执行。我该怎么做?
- mysql - MySQL 在“表”上更新之后/之前在同一个“表”上设置最后一次更新
- json - SyntaxError:位置 Y 处 JSON 中的意外标记 X
- d3.js - 带盒子的 D3 树
- angular - 使用角材料垫菜单时的叠加位置错误
- javascript - 单击按钮快速错误 JavaScript
- html - 弯曲方向属性