开发者

How do I change the value of submitted form data using form object and redisplay it?

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 c开发者_Go百科an 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 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜