【问题标题】:Using cleaned_data on forms in django在 Django 中的表单上使用cleaned_data
【发布时间】:2011-05-08 02:40:10
【问题描述】:

在传递 POST/GET 提交的输入值之前设置 cd = form.cleaned_data 有什么意义?

这有什么意义,为什么有必要? (如果是的话)

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    在传递输入值之前没有必要使用表单的 .cleaned_data 属性,如果在绑定表单中调用 .is_valid() 之前执行此操作或尝试以未绑定的表单,read more about Form.cleaned_data

    此外,通常最好将表单数据的使用抽象到表单方法中以封装逻辑

    在您看来,您应该使用表单的传统方式是这样的:

    if request.method == 'POST':
      form = MyForm(request.POST) # Pass the resuest's POST/GET data
      if form.is_valid():         # invoke .is_valid
        form.process() # look how I don't access .cleaned_data in the view
    

    以您的形式:

    class MyForm(forms.Form):
      my_field = forms.CharField()
    
      def process(self):
        # Assumes .cleaned_data exists because this method is always invoked after .is_valid(), otherwise will raise AttributeError
        cd = self.cleaned_data 
        # do something interesting with your data in cd
        # At this point, .cleaned_data has been used _after_ passing the POST/GET as form's data
    

    【讨论】:

    • +1 提到 Django 如果您在调用cleaned_data 之前尝试访问cleaned_data 将引发 AttributeError 有趣的事实:6 年后它仍然这样做......
    • @pentix Yip。您认为他们可能使用了 FormNotValidated 错误?
    • 3 年后仍然如此
    【解决方案2】:

    一旦 is_valid() 返回 True,您就可以安全地处理表单提交,因为它符合表单定义的验证规则。虽然此时您可以直接访问 request.POST,但最好访问 form.cleaned_data。这些数据不仅已经过验证,还会为您转换成相关的 Python 类型。

    Processing the data from a form

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      相关资源
      最近更新 更多