I have written myself a form:
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)
Now I know that I would not have to explicitly set reuqired=True but bear it for now please.
Anyways, let’s press on.
Now since I hate doing validation and so on in the view I just defined an update function for that form:
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']
...
and then in my view call it like so:
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()
...
Now the problem is that If I don’t type anything in the form the form is returned as is without displaying any errors like it ought to. I also know that it wont do anything because:
https://docs.djangoproject.com/en/1.3/ref/forms/validation/
In fact, Django will currently completely wipe out the cleaned_data dictionary if there are any errors in the form. However, this behavior may change in the future, so it’s not > a bad idea to clean up after yourself in the first place.
if i try:
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
I get the errors that I would have liked to see in the template.
I also already tried:
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
What exactly am I doing wrong?
UPDATE:
in my view:
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()
and in my form remove if self.is_valid()
Django has build in validation so you don’t need to rewrite it:
and in your view:
note that you call is_valid() in the view, not the form.
If you want to perform so more complicated validation on either individidual fields or on a grouping of fields, you can overwrite the forms
clean()andclean_[field_name]()methods.See here:
https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute