Essentially I want to sanitize some data a user submits in a form when I redisplay it if there is an error. This is easy to do if I am extracting the data from a form object. I can override the clean() method and manipulate the data. I can also set the .initial value for the first time it is displayed. However, I cannot find a way of manipulating the form data that is going to redisplayed on error. For example, say a user submits a phone number of "123 456 test test 7890”, I want to be able to strip out the non-alphanumeric characters(that is easy) and show them just the numbers “1234567890” in the form field.
If you are extending your form from a ModelForm, use the instance keyword argument. Here we pass either an existing instance or a new one, depending on whether we're editing or adding an existing article. In both cases the author field is set on the instance, so commit=False is not required.
To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message. You also need to specify the data type using the Content-Type: application/x-www-form-urlencoded request header.
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.
If the data is coming from a request (which is the case if you are using a view) the form.data
dictionary will be a QueryDict
which is supposed to be immutable. Thankfully you can hack your way into changing it by copying it first:
self.data = self.data.copy()
self.data['phone_number'] = 1234567890
If you are changing directly a form instance that is not from a view's request, you can change the form.data
dictionary (it's a simple dictionary object this way) directly like so:
# Don't need to copy `data` first
self.data['phone_numer'] = 123456789
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