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

时间:2014-03-05 21:46:45

标签: python django

form = ContactForm(request.POST)

# how to change form fields' values here?

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

在验证数据之前,有没有一种方法可以修剪空白,修改部分/所有字段等

2 个答案:

答案 0 :(得分:14)

你应该通过调用QueryDict来使request.POST(copy的实例)变为可变,然后更改值:

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)

您也可以尝试使用@Controller @RequestMapping("/") public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/insert", method = RequestMethod.GET) public String insert(){ studentService.insertStudent(new Student(01, "Crabime", 22)); return "hello"; } }

  1. 首先,将request.query_params的{​​{1}}属性设置为_mutable
  2. 更改所需的所有参数。

    query_params
  3. 这样做的好处是可以避免使用True

    的开销