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()
Related
I have a similar issue as this question about validating data in the Django REST Framework outside of a serializer:
Raise Validation Error In Pre_Save Using Django Rest Framework
My code:
def pre_save(self, obj):
data = self.request.DATA['users']
for user in data:
if not user in allowed_users:
raise ParseError('An unpermitted user has been included')
From the trace it looks like it's trying to send the response but it fails with:
"" needs to have a value for field before this many-to-many relationship can be used.
UPDATE:
I moved raising the ParseError into a get_serializer_class() method like so:
def get_serializer_class(self):
if 'users' in self.request.DATA:
# make sure the users are allowed
data = self.request.DATA['users']
for user in data:
if not user in allowed_users:
raise ParseError(detail='Unpermitted user')
return serializer
And this raises the exception, however, it does not return it using the REST framework's JSON response. Rather I get the django stack trace and a 500 error, which is not good.
Thanks!
Have a look at APIView's handle_exception — this is where DRF processes exceptions raised during the request.
From the docs:
The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django's Http404 and PermissionDenied exceptions, and returns an appropriate error response.
If you need to customize the error responses your API returns you should subclass this method.
So you need to override this to handle ParseError exceptions too.
Also check out the DRF docs on Exceptions.
I hope that helps.
When the exception is raised in the pre_save method(), post_save(), or even in a post() method for the viewclass, it was being handled correctly by Django-REST-Framework. Had I been using curl or similar, the error would have been returned correctly.
This actually is a bug in the browsable API, which is what I was using to test - sending the data using the "Raw data" form. When trying to render the html response, DRF apparently tries to capture the "context" of the post. In this case, it wanted the saved/completed post.
That did not exist, so a Django rendering error was being thrown and that confused me.
When testing using curl, the response was accurate.
Note that putting it in the get_serializer_class() like I did caused it to go outside of the DRF exception handler so Django rendered it correctly and showed the error was being thrown correctly.
I seem to have hit a wall full of puzzling results when trying to deal with the following use case:
URL: '^api/event/(?P<pk>[0-9]+)/registration$'
payload: {"registered": "true"} or {"registered": "false"}
I retrieve the event object corresponding to the given pk, and then based on that I want:
in a GET request to retrieve whether the authenticated user is registered or not
in a PUT to change the registration state.
Everything works fine until the point where I want to process the incoming payload in the PUT request. I've tried creating a serializer like this:
class RegistrationSerializer(serializers.Serializer):
registered = fields.BooleanField()
and call it from an APIView's put method with:
serializer = RegistrationSerializer(data=request.DATA)
but it doesn't work and serializer.data always contains `{"registered": False}
From a shell I tried another isolated test:
>>> rs = RegistrationSerializer(data={'registered':True})
>>> rs
<app.serializers.RegistrationSerializer object at 0x10a08cc10>
>>> rs.data
{'registered': False}
What am I doing wrong? What would be the best way to handle this use case?
You need to call rs.is_valid() first, before accessing rs.data.
Really the framework ought to raise an exception if you don't do so.
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
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.
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.