Dav*_*542 14 django django-forms
在传递POST/GET提交的输入值之前,设置cd = form.cleaned_data有什么意义?有什么意义,为什么有必要(如果是这样的话)?
Jj.*_*Jj. 25
在传递输入值之前没有必要使用表单的.cleaned_data属性,如果在以绑定形式调用.is_valid()之前执行此操作,或者如果您尝试以未绑定的形式访问它,则会引发AttributeError,阅读有关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
Run Code Online (Sandbox Code Playgroud)
在你的形式:
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
Run Code Online (Sandbox Code Playgroud)