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

前端 未结 2 1014
天涯浪人
天涯浪人 2021-02-19 18:05
form = ContactForm(request.POST)

# how to change form fields\' values here?

if form.is_valid():
    message = form.cleaned_data[\'message\']

Is there

2条回答
  •  眼角桃花
    2021-02-19 18:23

    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

提交回复
热议问题