|
1 | 1 | import json |
2 | 2 |
|
3 | | -from rest_framework.exceptions import ValidationError |
4 | 3 | from rest_framework.fields import MISSING_ERROR_MESSAGE |
5 | 4 | from rest_framework.relations import * |
6 | 5 | from django.utils.translation import ugettext_lazy as _ |
|
10 | 9 | get_resource_type_from_queryset, get_resource_type_from_instance |
11 | 10 |
|
12 | 11 |
|
13 | | -class HyperlinkedRelatedField(HyperlinkedRelatedField): |
14 | | - """ |
15 | | - This field exists for the sole purpose of accepting PKs as well as URLs |
16 | | - when data is submitted back to the serializer |
17 | | - """ |
18 | | - default_error_messages = { |
19 | | - 'required': _('This field is required.'), |
20 | | - 'no_match': _('Invalid hyperlink - No URL match.'), |
21 | | - 'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'), |
22 | | - 'does_not_exist': _('Invalid hyperlink - Object does not exist.'), |
23 | | - 'incorrect_type': _('Incorrect type. Expected URL string, received {data_type}.'), |
24 | | - 'pk_does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'), |
25 | | - 'incorrect_pk_type': _('Incorrect type. Expected pk value, received {data_type}.'), |
26 | | - } |
27 | | - |
28 | | - def __init__(self, **kwargs): |
29 | | - self.pk_field = kwargs.pop('pk_field', None) |
30 | | - super(HyperlinkedRelatedField, self).__init__(**kwargs) |
31 | | - |
32 | | - def to_internal_value(self, data): |
33 | | - try: |
34 | | - # Try parsing links first for the browseable API |
35 | | - return super(HyperlinkedRelatedField, self).to_internal_value(data) |
36 | | - except ValidationError: |
37 | | - if self.pk_field is not None: |
38 | | - data = self.pk_field.to_internal_value(data) |
39 | | - try: |
40 | | - return self.get_queryset().get(pk=data) |
41 | | - except ObjectDoesNotExist: |
42 | | - self.fail('pk_does_not_exist', pk_value=data) |
43 | | - except (TypeError, ValueError): |
44 | | - self.fail('incorrect_pk_type', data_type=type(data).__name__) |
45 | | - |
46 | | - |
47 | 12 | class ResourceRelatedField(PrimaryKeyRelatedField): |
48 | 13 | self_link_view_name = None |
49 | 14 | related_link_view_name = None |
|
0 commit comments