Django 表单验证:制作“必需"有条件的? [英] Django form validation: making "required" conditional?
问题描述
我是 Django(和 Python)的新手,我正在尝试弄清楚如何对表单验证的某些方面进行条件化.在这种情况下,应用程序有一个 HTML 界面,用户可以在其中从小部件中选择日期和时间.表单对象上的 clean
方法获取时间和日期字段的值并将它们转换回 datetime
.
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
.
除了 HTML 界面,还有一个 iPhone 客户端调用应用程序,我想传入一个 UNIX 时间戳样式的时间值.
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)
如何使 foo_date
和 foo_time
成为必需的除非 foo_timestamp
已提供?
How do I make foo_date
and foo_time
required unless foo_timestamp
is provided?
推荐答案
这是通过表单上的 clean
方法完成的.但是,您需要将 foo_date
和 foo_time
设置为 required=False
,因为 clean
仅在每个字段之后调用已经过验证(另见 文档).
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屋!