尽管表单错误,Django表单仍然通过验证

时间:2014-11-06 18:11:00

标签: django forms validation

我想我可能会遗漏一些关于Django表单验证的内容,但我认为只有表单中没有错误,表单上运行is_valid才会返回true。

我正在尝试将其设置为如果未设置“endTime”或“duration”,则表单返回false。

class NewShiftForm(forms.Form):
    recursionChoices = (('1','Once'),('2','Twice'),('4','Four times'),('10','Ten times'))
    endTime = forms.CharField(max_length=16, required=False)
    duration = forms.CharField(max_length=16, required=False)
    employee = UserModelChoiceField(queryset=User.objects.all(), required=True)
    recursion = forms.ChoiceField(choices=recursionChoices, widget=forms.Select())

    def clean(self):
        clean_duration = self.cleaned_data.get("duration")
        clean_endTime = self.cleaned_data.get("endTime")
        if not clean_duration and not clean_endTime:
            raise forms.ValidationError("You need either duration or end time")
        return self.cleaned_data

我认为我的清洁功能正常工作,因为当我在模板中渲染表单时,我看到表单错误(“您需要持续时间或结束时间”)。但是,在我看来,我将其设置为检查表单是否正在传递is_valid

def newShift(request, year, month, day, hour, minute, positionID):
    form = NewShiftForm()
    validity = "This form did not pass validation"
    if request.POST:
        form = NewShiftForm(request.POST)
        if form.is_valid:
           validity = "This form passed validation" 
    startTime = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), 0)
    year = int(year)
    position_name = Position.objects.filter(id=positionID)[0]
    return render(request, 'managers/newShift.html',{
        "form": form,
        "start": startTime,
        "position": position_name,
        'validity': validity,
    })

模板在POST之前显示“此表单未通过验证”的有效性。在POST提交后提交,并且“此表单已通过验证”。

如果表单出现表单错误,如何使表单验证失败?

非常感谢!

1 个答案:

答案 0 :(得分:1)

你需要

if form.is_valid():

而不是

if form.is_valid:

试试这个(简化版):

def newShift(request, year, month, day, hour, minute, positionID):       
   if request.POST:
      form = NewShiftForm(request.POST)
      if form.is_valid():
         print "This form passed validation"
         return render(request, 'managers/newShift.html',{
            "form": form,
         })
      else:
         print "This form did not pass validation"
         return render(request, 'managers/newShift.html',{
            "form": form,
         })
   else:
      # no POST request
      form = NewShiftForm() # unbound form
      return render(request, 'managers/newShift.html',{
            "form": form,
      })

您可能希望根据验证状态更改模板