【发布时间】: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