Modify value of a Django form field during clean()

前端 未结 7 1540
陌清茗
陌清茗 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:32

    I was setting a value to a specific field in another clean function, but it didnt work because of it was overwrited by the main clean function. In order to set the value and keep it :

    • There didnt work.
        def clean_tipo_cupon(self):
            tipo_cupon = self.cleaned_data['tipo_cupon']
            qscu = mdlcat.TipoCuponVenta.objects.filter(
                id=tipo_cupon, estado_id=1,
            )
            if not qscu.exists():
                wmessage = u'introducido no paso validación'
                raise forms.ValidationError(wmessage)
    
            qscu = qscu.first()
            if not qscu.default_owner is None:
                self.cleaned_data['default_owner'] = qscu.default_owner.id
    
            return tipo_cupon
    
    
    • Here, it worked like a charm.
        def clean(self):
            cleaned_data = super().clean()
            for item in self.fields.keys():
                if isinstance(cleaned_data.get(item), str):
                    cleaned_data[item] = cleaned_data.get(item).upper()
    
            # if a default owner is configured by coupon type
            # it will be assigned
            tipo_cupon = cleaned_data['tipo_cupon']
            qscu = mdlcat.TipoCuponVenta.objects.filter(
                id=tipo_cupon, estado_id=1,
            )
            qscu = qscu.first()
            if not qscu.default_owner is None:
                self.cleaned_data['default_owner'] = qscu.default_owner.id
    
            return cleaned_data
    

提交回复
热议问题