我自己写了一份表格:
class Autopoweroff_Form(forms.Form):
autopoweroff_groups = forms.CharField(required=True)
autopoweroff_groups_hosts = forms.CharField(required=True)
autopoweroff_groups_start = forms.CharField(required=True)
autopoweroff_groups_end = forms.CharField(required=True)
autopoweroff_groups_startup_delay = forms.CharField(required=True)
autopoweroff_groups_idle_time = forms.CharField(required=True)
现在我知道我不必明确设置reuqired = True,但现在请耐心等待。 无论如何,让我们继续。
既然我讨厌在视图中进行验证等等,我只是为该表单定义了更新函数:
def update(self, data):
if not self.is_bound and data is not None:
raise Exception()
if self.is_valid():
curr_group = self.cleaned_data['autopoweroff_groups']
...
然后在我的视图中称之为:
if request.method == 'POST':
form = Autopoweroff_Form(data=request.POST)
form.update(data=request.POST)
return HttpResponseRedirect('/admin/thin/create_autopoweroff')
else:
form = Autopoweroff_Form()
...
现在的问题是,如果我没有在表单中键入任何内容,表单将按原样返回,而不会显示任何错误。我也知道它不会做任何事情,因为:
https://docs.djangoproject.com/en/1.3/ref/forms/validation/
事实上,如果表单中有任何错误,Django目前将完全清除cleaning_data字典。但是,此行为可能在将来发生变化,因此不是>首先要清理自己的坏主意。
如果我尝试:
def update(self, data):
if not self.is_bound and data is not None:
raise Exception()
if self.is_valid():
curr_group = self.cleaned_data['autopoweroff_groups']
...
else:
print self.errors
我得到了我希望在模板中看到的错误。 我也试过了:
def clean_autopoweroff_groups(self):
autopoweoff_groups = self.cleaned_data.get('autopoweroff_groups', "")
if autopoweoff_groups == '':
print "Validation Error"
raise forms.ValidationError('Please Enter A Name')
return autopoweroff_groups
我究竟做错了什么?
更新: 在我看来:
if request.method == 'POST':
form = Autopoweroff_Form(data=request.POST)
if form.is_valid():
form.update(data=request.POST)
return HttpResponseRedirect('/admin/thin/create_autopoweroff')
else:
form = Autopoweroff_Form()
并在我的表单中删除self.is_valid()
答案 0 :(得分:0)
Django已经内置验证,因此您无需重写它:
class Autopoweroff_Form(forms.Form):
# I suggest not prefixing your fields with the name of the class
groups = forms.CharField(required=True)
hosts = forms.CharField(required=True)
start = forms.CharField(required=True)
end = forms.CharField(required=True)
delay = forms.CharField(required=True)
idle_time = forms.CharField(required=True)
并在您看来:
if request.method == 'POST':
form = Autopoweroff_Form(data=request.POST)
if form.is_valid():
return HttpResponseRedirect('/admin/thin/create_autopoweroff')
else:
form = Autopoweroff_Form()
请注意,您在视图中调用is_valid(),而不是表单。
如果要对单个字段或字段分组执行更复杂的验证,可以覆盖表单clean()
和clean_[field_name]()
方法。
见这里:
https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute