我在Djano中有一个选择菜单,在models.py中有这样的构建。
execution_time = models.IntegerField(
choices=((i, i) for i in (0, 15, 30, 45, 60)),
blank=False,
default=30,
verbose_name='estimated time'
)
我还在forms.py和clean方法中有一个文本字段(当用户在execution_time中选择0作为选项时出现)。
class DummyForm(forms.ModelForm):
admin_time = forms.CharField(
help_text=_('Enter If more than 60 minutes.'),
required=False,
widget=forms.TextInput(attrs={'class': 'fill-width'}))
def clean(self):
cleaned_data = super(DummyForm, self).clean()
admin_time = cleaned_data.get('admin_time')
if admin_time:
cleaned_data['execution_time'] = admin_time
return cleaned_data
select_ option(execution_time)的值被admin_time覆盖。但它没有得到验证。因为我在选择菜单中只有15,30,45,60。另外,我无法删除选择选项。 我应该如何更改验证,以便我不会收到类似“值80不是有效选择”的错误。
答案 0 :(得分:1)
错误输出的验证是在模型级别而不是表单级别。您需要在表单级别设置用户可用的选项,并允许模型接受模型上的任何数字。
class ExampleModel(models.Model):
execution_time = models.IntegerField(
blank=False,
default=30,
verbose_name='estimated time'
)
class DummyForm(models.ModelForm):
admin_time = forms.IntegerField(
help_text=_('Enter If more than 60 minutes.'),
required=False,
widget=forms.TextInput(attrs={'class': 'fill-width'}))
execution_time = forms.IntegerField(
widget=forms.Select(choices=((i, i) for i in (0, 15, 30, 45, 60)))
def clean(self):
cleaned_data = super(DummyForm, self).clean()
admin_time = cleaned_data.get('admin_time')
if admin_time:
cleaned_data['execution_time'] = admin_time
return cleaned_data