Skip to content

Enforce conflict response when requested PATCH resource object is unequal to endpoint #763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jan 23, 2020
18 changes: 18 additions & 0 deletions example/tests/test_model_viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,24 @@ def test_patch_requires_id(self):

self.assertEqual(response.status_code, 400)

def test_patch_requires_correct_id(self):
"""
Verify that 'id' is required to be passed in an update request.
"""
data = {
'data': {
'type': 'users',
'id': 3,
'attributes': {
'first-name': 'DifferentName'
}
}
}

response = self.client.patch(self.detail_url, data=data)

self.assertEqual(response.status_code, 409)

def test_key_in_post(self):
"""
Ensure a key is in the post.
Expand Down
10 changes: 10 additions & 0 deletions rest_framework_json_api/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ def parse(self, stream, media_type=None, parser_context=None):
if not data.get('id') and request.method in ('PATCH', 'PUT'):
raise ParseError("The resource identifier object must contain an 'id' member")

if request.method in ('PATCH', 'PUT'):
kwarg_name = view.lookup_url_kwarg if view.lookup_url_kwarg else view.lookup_field
if str(data.get('id')) != str(view.kwargs[kwarg_name]):
raise exceptions.Conflict(
"The resource object's id ({data_id}) does not match url ({url_id})".format(
data_id=data.get('id'),
url_id=view.kwargs[view.lookup_field]
)
)

# Construct the return data
serializer_class = getattr(view, 'serializer_class', None)
parsed_data = {'id': data.get('id')} if 'id' in data else {}
Expand Down