django - Reset field value in case of a ValidationError -
i have custom form field (subclassed charfield). underlying model has is_approved() method. if field approved (is_approved() returns true), raise validationerror , render field read only. drawback here html field has value entered (and cannot save due validationerror) , cannot change html field read only.
is there way change field’s value original one, form won’t complain? setting self.initial in field’s validate() method didn’t help.
update: after experimenting form class, implemented following clean() method:
def clean(self, *args, **kwargs): field_id, e in self.errors.items(): needs_reset = false error in e.as_data(): if error.code == 'field_approved': needs_reset = true if needs_reset: self.cleaned_data[field_id] = self.fields[field_id].field.value super(buildfillform, self).clean(*args, **kwargs) but still doesn’t reset field’s value.
i have found solution setting self.was_approved in field’s to_python() method:
def to_python(self, value): old_value = self.dbfield.value if ( self.dbfield.is_approved() , old_value != value): self.was_approved = true return '' if value none else value and using was_approved property change return value of bound_data():
def bound_data(self, data, initial): if self.was_approved: return initial else: return data with approach, remove clean() method mentioned in question, , same result desired: validation error, while rendered form has database value displayed.
Comments
Post a Comment