在django中的表单上使用cleaning_data [英] Using cleaned_data on forms in django

查看:134
本文介绍了在django中的表单上使用cleaning_data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在传递POST / GET提交的输入值之前,要设置cd = form.cleaned_data的要点是什么?这是什么意思,为什么有必要(如果是这样)?

解决方案

没有必要使用在传递输入值之前,表单的.cleaned_data属性,如果您在绑定表单中调用.is_valid()之前执行此操作,或者您尝试以未绑定的形式访问它,则会引发AttributeError 更多关于Form.cleaned_data



另外,为了封装逻辑,在表单方法中抽象使用表单的数据通常是个好主意。



在您的意见中,传统的您应该使用表单的方式是这样的:

  if request.method =='POST':
form = MyForm(request.POST)#传递resuest的POST / GET数据
如果form.is_valid():#invoke .is_valid
form.process()#看看我如何访问.cleaned_data在查看

您的形式:

  class MyForm(forms.Form):
my_field = forms.CharField()

def process(self):
#假设.cleaned_data存在,因为这个方法总是在.is_valid()之后调用,否则会引发AttributeError
cd = self.cleaned_data
#在cd
#中对数据进行有趣的事情在这一点上,已经使用.cleaned_data _after_将POST / GET作为窗体的数据传递


What is point of setting cd = form.cleaned_data before passing the input values of a POST/GET submission? What is the point of this and why is it necessary (if it is so)?

解决方案

It is not necessary to use the .cleaned_data attribute of a form before passing the input values, it will raise an AttributeError if you do it before calling .is_valid() in a bound form or if you try to access it in an unbound form, read more about Form.cleaned_data .

Also, it is usually a good idea to abstract the use of the form's data in a form method in order to encapsulate logic

In your views, the traditional way you should be using forms is like this:

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

in your form:

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

这篇关于在django中的表单上使用cleaning_data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆