本文介绍了在 clean() 期间修改 Django 表单字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向我的 Django 应用程序中的表单和自定义字段添加自定义验证.我希望能够在触发错误时修改字段的值.例如,如果出现错误,应重新显示表单,其中字段值已通过 clean() 更正,并显示错误消息下面的数据已更正.再次单击保存以确认这些更改是否正确"

I am adding custom validation to my forms and custom fields in my Django app. I would like to be able to modify the value of a field when triggering an error. For example, if there is an error, the form should be redisplayed with the field value corrected by clean() and an error message "Data has been corrected below. Click save again to confirm if these changes are OK"

我试过像这样在cleaned_data[] 中返回修改后的数据,但它不起作用.它正确显示错误,但在重新显示表单时,字段值不会使用更正的 HTML 进行更新.

I've tried returning the modified data in cleaned_data[] like this but it doesn't work. It displays the error correctly, but the field value is not updated with the corrected HTML when the form is redisplayed.

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

我也想对一个字段做同样的事情,但由于错误是由异常触发的,我没有机会返回更正后的值.和form clean()方法一样,错误显示正确,但是值没有更新.

I'd also like to do the same thing with a field, but since the errors are triggered by exception, I don't get a chance to return the corrected value. Like the form clean() method, the error is displayed correctly, but the value is not updated.

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

推荐答案

在clean方法中改变self数据来改变显示的值

change self data in the clean method to change the value which gets displayed

这篇关于在 clean() 期间修改 Django 表单字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 23:20