form = ContactForm(request.POST)
# how to change form fields' values here?
if form.is_valid():
message = form.cleaned_data['message']
Is there a good way to trim whitespace, modify some/all fields etc before validating data?
Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
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.
Firstly, we will need a Django model to perform validation. Next, we need a validator function that will take the field value and return it if it satisfies the custom validation; otherwise, it returns an error message. Finally, we need to integrate the validator function with the appropriate field in the Django model.
( is_valid() runs validation routines for all fields on the form. When this method is called, if all fields contain valid data, it will: return True. place the form's data in its cleaned_data attribute.)
You should make request.POST(instance of QueryDict
) mutable by calling copy
on it and then change values:
post = request.POST.copy() # to make it mutable
post['field'] = value
# or set several values from dict
post.update({'postvar': 'some_value', 'var': 'value'})
# or set list
post.setlist('list_var', ['some_value', 'other_value']))
# and update original POST in the end
request.POST = post
QueryDict
docs - Request and response objects
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