在 Django 中的表单上使用cleaned_data [英] Using cleaned_data on forms in django
问题描述
在传递 POST/GET 提交的输入值之前设置 cd = form.cleaned_data
有什么意义?
What is the point in setting cd = form.cleaned_data
before passing the input values of a POST/GET submission?
这有什么意义,为什么有必要?(如果是的话)
What is the point in this and why is it necessary? (if it is so)
推荐答案
在传递输入值之前不需要使用表单的 .cleaned_data 属性,如果在调用 .is_valid() 以绑定形式或者如果您尝试以未绑定形式访问它,阅读有关 Form.cleaned_data 的更多信息 .
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
在您的表单中:
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 中的表单上使用cleaned_data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!