Reputation: 3564
I think I might be missing something about Django's form validation, but I thought that running is_valid on a form would return true only if the form had no errors in it.
I'm trying to make it so that the form returns false if either "endTime" or "duration" are not set.
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
I think my clean function is working properly, as I see the form error ("You need either duration or end time") when I render the form in my template. However, in my view, I set it to check whether or not the form is passing 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,
})
The template displays validity as "This form did not pass validation" before POST. submission, and "This form passed validation" after POST submission.
How do I make it so that the form fails validation if it has form errors?
Thanks so much!
Upvotes: 0
Views: 144
Reputation: 37876
you need
if form.is_valid():
instead of
if form.is_valid:
and try this one (simplified version):
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,
})
and you might want to change templates according to validation state
Upvotes: 1