Skip to content

Commit

Permalink
add forma validation to pust request
Browse files Browse the repository at this point in the history
  • Loading branch information
pavlov99 committed Mar 26, 2015
1 parent 5b939eb commit ad63ed9
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
6 changes: 6 additions & 0 deletions jsonapi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,12 @@ def handler_view_put(self, resource, **kwargs):

try:
data = resource.put(**kwargs)
if "errors" in data:
response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=400)
return response

response = HttpResponse(
json.dumps(data, cls=DatetimeDecimalEncoder),
content_type=self.CONTENT_TYPE, status=200)
Expand Down
16 changes: 13 additions & 3 deletions jsonapi/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,16 +394,26 @@ def put(cls, request=None, **kwargs):
)
raise JSONAPIError(statuses.HTTP_403_FORBIDDEN, msg)

objects = []
forms = []
for item in items:
if 'links' in item:
item.update(item.pop('links'))
Form = cls.Meta.form or cls.get_form(item.keys())
instance = objects_map[item["id"]]
form = Form(item, instance=instance)
objects.append(form.save())
forms.append(form)

data = [cls.dump_document(o) for o in objects]
if not form.is_valid():
response = {
"errors": [{
"status": 400,
"title": "Validation Error",
"data": form.errors
}]
}
return response

data = [cls.dump_document(f.save()) for f in forms]

if not is_collection:
data = data[0]
Expand Down
27 changes: 27 additions & 0 deletions tests/testapp/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,33 @@ def test_update_model_authentication(self):
user = User.objects.get(id=self.user.id)
self.assertEqual(user.email, "email@example.com")

def test_update_model_validation_error(self):
author = mixer.blend('testapp.author')
response = self.client.put(
'/api/author/{}'.format(author.id),
json.dumps({
"data": {
"id": author.id,
"name": "a" * 101,
},
}),
content_type='application/vnd.api+json',
HTTP_ACCEPT='application/vnd.api+json'
)
self.assertEqual(response.status_code, 400)

expected_data = {
"errors": [{
"status": 400,
"title": "Validation Error",
"data": {'name': ['Ensure this value has at most 100 ' +
'characters (it has 101).']},
}]
}

data = json.loads(response.content.decode("utf-8"))
self.assertEqual(data, expected_data)

def test_delete_model(self):
author = mixer.blend("testapp.author")
response = self.client.delete(
Expand Down

0 comments on commit ad63ed9

Please sign in to comment.