Modify value of a Django form field during clean()

前端 未结 7 1513
陌清茗
陌清茗 2020-12-29 04:42

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, i

7条回答
  •  遥遥无期
    2020-12-29 05:15

    We can't redireclty edit request.data because it's an immutable dict. You need to copy it, do your stuff and return it.

    But after differentes solutions I find this way (tested in Django 2.2.6)

    class MyForm(ModelForm):
    
        def clean(self):
            cleaned_data = super(MyForm, self).clean()
            self.instance.field = 'value'
            return cleaned_data
    
    

提交回复
热议问题