期间修改Django表单字段的值

期间修改Django表单字段的值

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

问题描述

我在我的Django应用程序的表单和自定义字段中添加了自定义验证。我想在触发错误时修改一个字段的值。例如,如果出现错误,则应使用clean()更正的字段值重新显示表单,并显示错误消息数据已被更正,请再次单击以确认这些更改是否正常



我已经尝试以clean_data []的形式返回修改后的数据,但这不行。它正确显示错误,但是当重新显示表单时,更改的HTML不会更新字段值。

  class T34AtividadeForm 
def clean(self):
#返回清除的html
错误,html = fix_imgs(clean_data.get(a34_descricao))
如果错误:
msg = u'Data以下已更正。再次单击保存以确认这些更改是否正常;
self._errors ['a34_descricao'] = ErrorList([msg])
#这不工作
cleaning_data [a34_descricao] = html
#工作
self.a34_descricao = html

返回clean_data

我也想用一个字段做同样的事情,但是由于错误是由异常触发的,所以我没有机会返回更正的值。像clean()方法一样,错误显示正确,但值不会更新。

  class HTMLField(CharField) :
widget = HTMLTextarea

def clean(self,value):
value = super(HTMLField,self).clean(value)
error,html = fix_imgs (值)
如果错误:
#这不工作
self.value = html
raise forms.ValidationError(u'Data已在下面更正,再次单击保存确认这些更改是否正常。')
return html


解决方案>

更改清除方法中的自我数据以更改显示的值


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"

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

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
解决方案

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

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

08-04 23:20