我在我的Django应用程序中添加自定义验证到我的表单和自定义字段.我希望能够在触发错误时修改字段的值.例如,如果出现错误,则应使用clean()更正的字段值重新显示表单,并显示错误消息"下面已更正数据.再次单击"保存以确认这些更改是否正常"
我已经尝试在cleaning_data []中返回修改后的数据,但它不起作用.它正确显示错误,但在重新显示表单时,不会使用更正后的HTML更新字段值.
class T34AtividadeForm(ModelForm): def clean(self): # Return cleaned html error,html = fix_imgs(cleaned_data.get("a34_descricao")) if error: msg = u'Data has been corrected below. Click save again to confirm if these changes are OK'; self._errors['a34_descricao'] = ErrorList([msg]) # This doesn't work cleaned_data["a34_descricao"] = html # This doesn't work either self.a34_descricao = html return cleaned_data
我也喜欢用字段做同样的事情,但由于错误是由异常触发的,我没有机会返回修正后的值.与表单clean()方法一样,错误显示正确,但值不会更新.
class HTMLField(CharField): widget = HTMLTextarea def clean(self, value): value = super(HTMLField,self).clean(value) error,html = fix_imgs(value) if error: # This doesn't work self.value = html raise forms.ValidationError(u'Data has been corrected below. Click save again to confirm if these changes are OK.') return html
小智.. 6
更改clean方法中的self数据以更改显示的值
更改clean方法中的self数据以更改显示的值