Reputation: 21
This morning I was developing my Django REST API with Tastypie when I encountered a problem I don't know how to solve. I have a Resource that looks like this:
class UserSignUpResource(ModelResource):
class Meta:
object_class = User
queryset = User.objects.all()
allowed_methods = ['post']
include_resource_uri = False
resource_name = 'newuser'
serializer = CamelCaseJSONSerializer(formats=['json'])
authentication = Authentication()
authorization = Authorization()
always_return_data = True
validation = FormValidation(form_class=UserSignUpForm)
This Resource receives JSON-formated data and creates a new Resource (I only permmit POST ops). So, first the data is checked through the:
validation = FormValidation(form_class=UserSignUpForm)
The thing is, that if data is incorrect, it does return a ImmediateHttpResponse. But I would want to capture this exception and create a JSON like this:
{"status": False, "code": 777, "errors": {"pass":["Required"], ...}
So, I override my wrap_view and add the following code snippet:
except ImmediateHttpResponse, e:
bundle = {"code": 777, "status": False, "error": e.response.content}
return self.create_response(request, bundle, response_class = HttpBadRequest)
This code captures the exception properly, but it has a problem. e.response contains a unicode string with the errors. So, the response it finally gives is
{"code": 777,
"error": "{\"birthdayDay\": [\"This field is required.\"],
\"birthdayMonth\": [\"This field is required.\"],
\"birthdayYear\": [\"This field is required.\"],
\"csrfmiddlewaretoken\": [\"This field is required.\"],
\"email\": [\"This field is required.\"],
\"email_2\": [\"This field is required.\"],
\"firstName\": [\"This field is required.\"],
\"gender\": [\"This field is required.\"],
\"lastName\": [\"This field is required.\"],
\"password1\": [\"This field is required.\"]}",
"status": false}
That damned \ and the first " are killing me. On the other side, the Frontend developer, who is working with AJAX, tells me that he can't parse the errors.
Am I doing anything wrong here? Does anybody knows how to convert the exception response, into a JSON?
Upvotes: 1
Views: 1707
Reputation: 9190
You probably want to send the response content as json, not as a serialized json string:
import json
bundle = {"code": 777, "status": False, "error": json.loads(e.response.content)}
Upvotes: 2