Django表单验证:制作“必需”条件? [英] Django form validation: making "required" conditional?
问题描述
我是Django(和Python)的新手,我正在试图找出如何对表单验证的某些方面进行条件化。在这种情况下,有一个应用程序的HTML接口,用户可以从窗口小部件中选择日期和时间。表单对象上的 clean
方法采用时间和日期字段的值,并将其重新转换为 datetime
。
除了HTML界面,还有一个iPhone客户端调用应用程序,我想传递UNIX时间戳样式的时间值。 / p>
我的表单代码如下所示:
class FooForm(forms。 ModelForm)
foo_date = forms.CharField(required = True,widget = forms.RadioSelect(choices = DATE_CHOICES))
foo_time = forms.CharField(required = True,widget = SelectTimeWidget())
foo_timestamp = forms.CharField(required = False)
如何使 foo_date
和 foo_time
需要,除非 foo_timestamp
这是使用表单上的 clean
方法完成的。您需要将 foo_date
和 foo_time
设置为 required = False
但是,因为 clean
只有在每个字段都被验证之后才被调用(另见文档)。
$ $ $ $ $ $ $ $ $
def clean(self):
data = self.cleaned_data
如果data.get('foo_timestamp',无)或(data.get('foo_date',无)和data.get('foo_time',无)):
返回数据
else:
raise forms.ValidationError('提供日期和时间或时间戳')
I'm new to Django (and Python), and am trying to figure out how to conditionalize certain aspects of form validation. In this case, there's a HTML interface to the application where the user can choose a date and a time from widgets. The clean
method on the form object takes the values of the time and date fields and turns them back into a datetime
.
In addition to the HTML interface, there's also an iPhone client making calls into the application, and I'd like to pass a UNIX timestamp-style time value in.
My form code looks like this:
class FooForm(forms.ModelForm):
foo_date = forms.CharField(required=True, widget=forms.RadioSelect(choices=DATE_CHOICES))
foo_time = forms.CharField(required=True, widget=SelectTimeWidget())
foo_timestamp = forms.CharField(required=False)
How do I make foo_date
and foo_time
required unless foo_timestamp
is provided?
This is done with the clean
method on the form. You need to set foo_date
and foo_time
to required=False
, though, because clean
is only called after every field has been validated (see also the documentation).
class FooForm(forms.Form)
# your field definitions
def clean(self):
data = self.cleaned_data
if data.get('foo_timestamp', None) or (data.get('foo_date', None) and data.get('foo_time', None)):
return data
else:
raise forms.ValidationError('Provide either a date and time or a timestamp')
这篇关于Django表单验证:制作“必需”条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!