I have a django form that I want to custom clean. Instead of just specifying an error message like here (Django form and field validation), I'd like to just alter the field myself. I tried severl ways, but keep running into error like cleaned_data is immutable.
So to solve this I made a copy, changed it and reassigned it to self. Is this the best way to do this? Could/should I have handled this in the view? Making a copy seems poor form but I keep running into 'immutable' road blocks. Sample code below where I simply check if the subject has '--help' at the end, and if not add it. Thanks
def clean(self):
cleaned_data=self.cleaned_data.copy()
subject=cleaned_data.get['subject']
if not subject.endswith('--help'):
cleaned_data['subject']=subject+='--help'
self.cleaned_data=cleaned_data
return self.cleaned_data
form. 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).
The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.
You can use is_valid() when required to validate complete form-data. This validation will check for Python-datatypes. This function will return True or False (Python Data Types) in return.
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.
The correct way to deal with this is by using the field specific clean methods.
Whatever you return from the clean_FOO
method is what the cleaned_data
will be populated with by the time it gets to the clean
function.
Do the following instead:
def clean_subject(self):
data = self.cleaned_data.get('subject', '')
if not data:
raise forms.ValidationError("You must enter a subject")
# if you don't want this functionality, just remove it.
if not data.endswith('--help'):
return data += '--help'
return data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With