Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form: what is the best way to modify posted data before validating?

Tags:

python

django

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?

like image 587
Bob Avatar asked Mar 05 '14 21:03

Bob


People also ask

How does Django validate form 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.

What is clean method in Django?

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.

How can you validate Django model fields?

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.

Which of the following is true if all fields contain valid data when validation routines are run using Is_valid () method for a form?

( 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.)


1 Answers

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

like image 130
ndpu Avatar answered Nov 09 '22 09:11

ndpu