我有一个用于更新找到的项目的表格。该表单通过视图扩展了 Django 的 UpdateView。更新丢失物品和更新找到物品的表单使用相同的模板,但具有不同的视图和表单。它们共享相同的模板,因为大多数字段都相同。
我正在尝试为表单添加一些自定义表单验证,以特别更新找到的项目。此验证特定于找到的物品,不适用于丢失的物品。我在一个干净的函数中进行了验证,该函数FoundUpdateForm检查是否满足了所需的条件,如果不满足条件,则引发 ValidationError。即使这里有验证,我也想将它添加到 JavaScript 文件中。
我曾尝试在与表单上的元素相关联的 JavaScript 文件中创建变量,但没有成功。我试过使用var staff_type = document.getElementById('staff_type'),var staff_type = document.getElementById('FoundUpdateForm').elements.namedItem('staff_type')以及其他一些变体。我正在处理的主要问题是如何在没有 ID 的情况下获取表单。我已经研究过在 forms.py 中为表单分配一个 ID,但从我的发现来看,至少它似乎不能以这种方式完成。
我想尽可能避免添加到模板中,因为如前所述,该模板被多个表单使用。此外,由于表单扩展了 UpdateView 模板,因此该模板能够{{ form.as_p }}使用 p 标签来呈现表单的字段。因为元素以这种方式呈现到页面上,Django 为每个元素分配了自己的 ID,但表单本身并没有分配一个 ID。
表格.py:
class FoundUpdateForm(ModelForm):
Found._meta.get_field('staff_type').formfield(widget=forms.RadioSelect())
def clean(self):
cleaned_data = super(FoundUpdateForm, self).clean()
staff_type = cleaned_data.get('staff_type')
witness = cleaned_data.get('witness')
res_type = cleaned_data.get('res_type')
name_of_the_individual_claiming_item = cleaned_data.get('name_of_the_individual_claiming_item')
phone_number = cleaned_data.get('phone_number')
if not staff_type:
raise forms.ValidationError("Please fill out Type of Employee Resolving Item.")
if staff_type == 'student' and not witness:
raise forms.ValidationError("Student staff resolving lost items are required to have a witness.")
if res_type.name == 'Picked up':
if not name_of_the_individual_claiming_item:
raise forms.ValidationError("If person is picking up item, the individual's name is required.")
if not phone_number:
raise forms.ValidationError("If person is picking up item, the individual's phone number is required.")
if not witness:
raise forms.ValidationError("If person is picking up item, a witness is required.")
}
FFIVE
相关分类