Django form: what is the best way to modify published data before validation?

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 spaces, change some / all fields, etc. before checking the data?

+4
source share
2 answers

You should make request.POST (instance QueryDict) change by calling copyon it, and then change the 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

QueryDictdocs - Request and response objects

+8
source

You can also try using request.query_params.

  • First, set _mutablethe value of query_paramsvalue True.
  • Change all the necessary parameters.

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

, request.POST.copy().

+1

Source: https://habr.com/ru/post/1530312/


All Articles