21
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?

3 Answers 3

40

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

1
  • 1
    That's what I've been looking for hours, thank you very much!
    – Bob
    Commented Mar 5, 2014 at 22:49
7

You could also try using request.query_params.

  1. First, set the _mutable property of the query_params to True.

  2. Change all the parameters you want.

    request.query_params._mutable = True
    request.query_params['foo'] = 'foo'
    

The advantage here is you can avoid the overhead of using request.POST.copy().

4
  • 1
    That's a feature of the Django REST framework. It doesn't ship with Django itself.
    – yofee
    Commented Mar 31, 2017 at 16:50
  • 1
    django has request.POST._mutable with the same functionality Commented Jun 12, 2020 at 13:10
  • 1
    Anyone with privileges, please correct the typo. request.quer_params['foo'] = 'foo' to request.query_params['foo'] = 'foo'
    – mitsu
    Commented Mar 10, 2022 at 3:47
  • 1
    @mitsu After editing i saw your comment 😀 Commented Dec 22, 2022 at 0:19
1

You can do the following (as suggested by Antony Hatchkins)

If using DRF

request.data._mutable = True
request.data['key'] = value

In Django

request.POST._mutable = True
request.POST['key'] = value

Not the answer you're looking for? Browse other questions tagged or ask your own question.