Python Django检查单个字段是否有错误且未运行clean()?
在django的Python Django检查单个字段是否有错误且未运行clean()?,python,django,Python,Django,在django的clean() 我不想手动检查是否存在必填字段: def clean(): cleaned_data = super().clean() half_day = cleaned_data.get('half_day') start_date = cleaned_data.get('start_date') end_date = cleaned_data.get('end_date') if start_date and end_date:
clean()
我不想手动检查是否存在必填字段:
def clean():
cleaned_data = super().clean()
half_day = cleaned_data.get('half_day')
start_date = cleaned_data.get('start_date')
end_date = cleaned_data.get('end_date')
if start_date and end_date:
if half_day:
if start_date != end_date:
self.add_error(
'half_day',
'Start and end date must be the same'
)
如果start\u date
和end\u date
声明为blank=False,null=False
(默认值),则可以执行以下操作:
def clean(self):
cleaned_data = super(MyModelForm, self).clean()
if not self.is_valid():
return cleaned_data
if cleaned_data.get('half_day'):
if cleaned_data['start_date'] != cleaned_data['end_date']:
self.add_error(
'half_day',
'Start and end date must be the same'
)
return cleaned_data
超级清理将返回带有错误的请求到模板,您不必检查字段是否有值。您上面的代码看起来很好。这是来自.assert myform.is_valid()==true的标准方法。注意:我还没有使用2.0。我看到超级调用可以不那么冗长:)是的,这是python3.6的一个新特性!那么你能接受这个答案吗,或者还有更多的答案吗?