Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify value of a Django form field during 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"

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 
like image 552
gerdemb Avatar asked Mar 17 '09 13:03

gerdemb


People also ask

What does cleaned data do in Django?

cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).

How do you make a field non editable in Django?

django-forms Using Model Form Making fields not editable Django 1.9 added the Field. disabled attribute: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

How can you validate Django model fields?

to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)


2 Answers

It is possible to modify a value of a field during clean() if you update self.data attribute of a Form. self.data is an instance of the QueryDict class. By default, querydicts are immutable. To make them mutable, you should use .copy() method. From the documentation:

The QueryDicts at request.POST and request.GET will be immutable when accessed in a normal request/response cycle. To get a mutable version you need to use QueryDict.copy()

self.data = self.data.copy() self.data['your_field'] = 'new value' 
like image 98
bilbohhh Avatar answered Sep 20 '22 22:09

bilbohhh


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

like image 32
user51463 Avatar answered Sep 23 '22 22:09

user51463