Django表单:在验证之前修改发布数据的最佳方法是什么?

Bob*_*Bob 5 python django

form = ContactForm(request.POST)

# how to change form fields' values here?

if form.is_valid():
    message = form.cleaned_data['message']
Run Code Online (Sandbox Code Playgroud)

验证数据之前,有没有一种很好的方法来修剪空白,修改一些/所有字段等?

ndp*_*dpu 14

您应该QueryDict通过调用copy它来使request.POST(instance of )可变,然后更改值:

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
Run Code Online (Sandbox Code Playgroud)

QueryDictdocs - 请求和响应对象


小智 7

您也可以尝试使用request.query_params.

  1. 首先,_mutable将 的属性设置query_paramsTrue

  2. 更改您想要的所有参数。

    request.query_params._mutable = True
    request.query_params['foo'] = 'foo'
    
    Run Code Online (Sandbox Code Playgroud)

这里的优点是您可以避免使用request.POST.copy().