is_valid() vs clean() django forms - django

In the process of finding a way to validate my django forms, I came across two methods is_valid() and clean() in the django docs. Can anyone enlighten me the how they are different/same? What are the pros and cons of either?
Thanks.

is_valid() calls clean() on the form automatically. You use is_valid() in your views, and clean() in your form classes.
Your clean() function will return self.cleaned_data which if you will notice in the following view is not handled by you as the programmer.
form = myforms.SettingsForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
#do stuff
You didn't have to do clean_data = form.is_valid() because is_valid() will call clean and overwrite data in the form object to be cleaned. So everything in your if form.is_valid() block will be clean and valid. The name field in your block will be the sanitized version which is not necessarily what was in request.POST.
Update
You can also display error messages with this. In clean() if the form data isn't valid you can set an error message on a field like this:
self._errors['email'] = [u'Email is already in use']
Now is_valid() will return False, so in the else block you can redisplay the page with your overwritten form object and it will display the error message if your template uses the error string.

Just wanted to add that the best way now to add an error to a form you're manually validating in is_valid() is to use Form.add_error(field, error) to conform with Django's ErrorDict object.
Doing
self._errors['field'] = ['error message']
will come out funky when rendering {{form.errors}}, like:
fielderror messsage
instead of the expected
field
-error message
so instead do:
self.add_error('email', 'Email is already in use')
See https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.add_error

Related

Testing for a ValidationError in Django

If I have a model called Enquiry with an attribute of email how might I check that creating an Enquiry with an invalid email raises an error?
I have tried this
def test_email_is_valid(self):
self.assertRaises(ValidationError, Enquiry.objects.create(email="testtest.com"))
However I get the Error
TypeError: 'Enquiry' object is not callable
I'm not quite getting something, does anybody know the correct method to test for email validation?
Django does not automatically validate objects when you call save() or create(). You can trigger validation by calling the full_clean method.
def test_email_is_valid(self):
enquiry = Enquiry(email="testtest.com")
self.assertRaises(ValidationError, enquiry.full_clean)
Note that you don't call full_clean() in the above code. You might prefer the context manager approach instead:
def test_email_is_valid(self):
with self.assertRaises(ValidationError):
enquiry = Enquiry(email="testtest.com")
enquiry.full_clean()

Inserting Errors into an InlineFormSet Custom Validator

I am using the following custom form validator to ensure that there is not more than one correct entry submitted to my application through an InlineFormSet.
class BaseAnswerFormSet(forms.models.BaseInlineFormSet):
def clean(self):
if any(self.errors):
return
if len([d['correct'] for d in self.forms if d['correct'].value()]) !=1:
raise forms.ValidationError("There must be one and only one correct answer")
return
This is working, as the form object that is presented will return False when evaluated as .is_clean() but there is no error returned. Here is what it shows up as when I use pdb in the view that handles the POST:
(Pdb) answerformset.is_valid()
False
(Pdb) answerformset.errors
[{}, {}, {}]
Shouldn't the raise forms.ValidationError("There must be one... create an error entry? I know that each of the empty dicts in the answerformset.errors list is for each of the answer forms, but I thought that there would be a non_field_error or something like that?
How can I get this clean function to return an error that I can display in a template? How can I add a non_field_error to this?
Please read Custom Formset Validation. Formset custom errors can be accessed using non_form_errors:
answerformset.non_form_errors()

Validation of modelformsets from modelforms

One view I have is using a modelform with custom field cleaning. One type of cleaning is checking if the user is trying to submit a change to a field that is already set to the value, and it works exactly how I want it to work by throwing a ValidationError. The problem of course is that I can only submit one form at a time, so I'd like to use a modelformset to submit multiple forms.
I know it is possible to override the modelformset's clean method, but I'm asking if it's possible to use the modelform's field cleaning methods on the modelformset?. Currently when I submit the modelformset with empty fields the is_valid() passes which seems strange to me...
I also would like to know "typically" where the custom modelformset validation code would go? I was thinking with the forms.py.
*Edit -- with answer. My httpResponseRedirect was allowing the form to be submitted without validation.
def mass_check_in(request):
# queryset
qs = Part.objects.none()
errlst=[]
c = {}
c.update(csrf(request))
# Creating a model_formset out of PartForm
PartFormSetFactory = modelformset_factory(model=Part,
form=PartForm,
formset=BasePartFormSet,
extra=2)
if request.method == 'POST':
PartFormSet = PartFormSetFactory(request.POST)
if PartFormSet.is_valid():
PartFormSet.save()
return http.HttpResponseRedirect('/current_count/')
else:
PartFormSet = PartFormSetFactory(queryset=qs, initial=[
{'serial_number':'placeholder',
},
{'serial_number':'placeholder'
}])
return render(request,'mass_check_in.html',{
'title':'Add Item',
'formset': PartFormSet,
'formset_errors': PartFormSet.non_form_errors(),
})
If you don't enter any data at all in one of the modelforms in your model formset, it will skip validation for that form; from the docs:
The formset is smart enough to ignore extra forms that were not changed.
You can actually disable this functionality though by forcing empty_permitted=False on the forms; see the accepted answer to this question for more: Django formsets: make first required?
Formsets do have their own clean method, but it's used to validate information between two or more forms in the formset, not for validating the individual forms themselves (which should be taken care of in the forms clean method - as you are doing now.
A formset has a clean method similar to the one on a Form class. This is where you define your own validation that works at the formset level:
Here's another similar question:
Django formset doesn't validate

redisplay django form after successfull call to is_valid() with custom error message

I have a django form that first validates its data through calling form.is_valid(). If its not, the form is redisplayed, with an error message regarding the invalid data.
Now if is_valid() is true, I try to save the data in an ldap backend. If the form.cleaned_data is not in correspondance with the ldap data type, I get an Exception from my ldap save method. Now what I would like to do in this case is to redisplay the form with an error message, just like the thing that happens after form.is_valid() returns false.
I tried reading some docs and also some django source, but could not find where I could hook into this.
An alternative would be to carefully build the form of (custom) form fields that would "guarantee" that the data is allready compliant to ldap syntax.
But I would like to make shure that I catch ldap syntax errors and display them in a convenient form. So if I could hook into that form redisplay mechanism would make me a happy little programmer :-)
Any ideas or hints?
Under your class for the form that extends forms.Form, add one of the following methods, assuming you have a is_valid_ldap_data() defined somewhere:
for a whole form:
def clean(self):
if !is_valid_ldap_data(self.cleaned_data.get("fieldname")):
raise forms.ValidationError("Invalid LDAP data type");
return self.cleaned_data
or for a single field:
def clean_fieldname(self):
if !is_valid_ldap_data(self.cleaned_data['fieldname'])):
raise forms.ValidationError("Invalid LDAP data type");
return self.cleaned_data['fieldname']
At your Form subclass implement custom field validation method
http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
Validation logic must go where it belongs. If form.is_valid() == True than form.cleaned_data must be valid. Just because code says so. You want to hide some of validation logic somewhere else -- and that is just bad practice.
It seems to me that you just have an additional step of validation.
You could, depending on which are your specific needs:
Put a validator on your fields, to check for simple things, or
Implement additional cleaning on your field or on multiple fields at once,
but in every case if the form is not valid for any reason (as in your case), is_valid should return False.

adding errors to Django form errors.__all__

How do I add errors to the top of a form after I cleaned the data? I have an object that needs to make a REST call to an external app (google maps) as a pre-save condition, and this can fail, which means I need my users to correct the data in the form. So I clean the data and then try to save and add to the form errors if the save doesn't work:
if request.method == "POST":
#clean form data
try:
profile.save()
return HttpResponseRedirect(reverse("some_page", args=[some.args]))
except ValueError:
our_form.errors.__all__ = [u"error message goes here"]
return render_to_response(template_name, {"ourform": our_form,},
context_instance=RequestContext(request))
This failed to return the error text in my unit-tests (which were looking for it in {{form.non_field_errors}}), and then when I run it through the debugger, the errors had not been added to the forms error dict when they reach the render_to_response line, nor anywhere else in the our_form tree. Why didn't this work? How am I supposed to add errors to the top of a form after it's been cleaned?
You really want to do this during form validation and raise a ValidationError from there... but if you're set on doing it this way you'll want to access _errors to add new messages. Try something like this:
from django.forms.util import ErrorList
our_form._errors["field_name"] = ErrorList([u"error message goes here"])
Non field errors can be added using the constant NON_FIELD_ERRORS dictionary key (which is __all__ by default):
from django import forms
errors = my_form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList())
errors.append("My error here")
In Django 1.7 or higher, I would do:
form.add_error(field_name, "Some message")
The method add_error was added in 1.7. The form variable is the form I want to manipulate and field_name is the specific field name or None if I want an error that is not associated with a specific field.
In Django 1.6 I would do something like:
from django.forms.forms import NON_FIELD_ERRORS
errors = form._errors.setdefault(field_name, form.error_class())
errors.append("Some message")
In the code above form is the form I want to manipulate and field_name is the field name for which I want to add an error. field_name can be set to NON_FIELD_ERRORS to add an error not associated with a specific field. I use form.error_class() to generate the empty list of error messages. This is how Django 1.6 internally creates an empty list rather than instantiate ErrorList() directly.
You should raise the validationerror.
Why not put the verification within the form's clean method
class ProfileForm(forms.Form):
def clean(self):
try:
#Make a call to the API and verify it works well
except:
raise forms.ValidationError('Your address is not locatable by Google Maps')
that way, you just need the standard form.is_valid() in the view.
You're almost there with your original solution. Here is a base Form class I built which allows me to do the same thing, i.e. add non-field error messages to the form:
from django import forms
from django.forms.util import ErrorDict
from django.forms.forms import NON_FIELD_ERRORS
class MyBaseForm(forms.Form):
def add_form_error(self, message):
if not self._errors:
self._errors = ErrorDict()
if not NON_FIELD_ERRORS in self._errors:
self._errors[NON_FIELD_ERRORS] = self.error_class()
self._errors[NON_FIELD_ERRORS].append(message)
class MyForm(MyBaseForm):
....
All my forms extend this class and so I can simply call the add_form_error() method to add another error message.
I'm not sure how horrible of a hack this is (I've only really worked on two Django projects up until this point) but if you do something like follows you get a separate error message that is not associated with a specific field in the model:
form = NewPostForm()
if something_went_horribly_wrong():
form.errors[''] = "You broke it!"
If the validation pertains to the data layer, then you should indeed not use form validation. Since Django 1.2 though, there exists a similar concept for Django models and this is certainly what you shoud use. See the documentation for model validation.