Python rest_framework.exceptions.ErrorDetail() Examples

The following are 12 code examples of rest_framework.exceptions.ErrorDetail(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.exceptions , or try the search function .
Example #1
Source File: test_views.py    From safe-relay-service with MIT License 6 votes vote down vote up
def test_token_view(self):
        random_address = Account.create().address
        response = self.client.get(reverse('v1:token', args=(random_address,)))
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
        self.assertEqual(response.data, {'detail': ErrorDetail(string='Not found.', code='not_found')})

        token = TokenFactory(address=random_address)
        response = self.client.get(reverse('v1:token', args=(random_address,)))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data, {'address': token.address,
                                         'logo_uri': token.get_full_logo_uri(),
                                         'default': token.gas,
                                         'name': token.name,
                                         'symbol': token.symbol,
                                         'description': token.description,
                                         'decimals': token.decimals,
                                         'website_uri': token.website_uri,
                                         'gas': token.gas}) 
Example #2
Source File: renderers.py    From kpi with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, data, accepted_media_type=None, renderer_context=None):

        # data should be str, but in case it's a dict, return as XML.
        # e.g. It happens with 404
        if isinstance(data, dict):
            # Force cast `ErrorDetail` as `six.text_type` because `dicttoxml`
            # does not recognize this type and treat each character as xml node.
            for k, v in data.items():
                if isinstance(v, ErrorDetail):
                    data[k] = str(v)

            # FIXME new `v2` list endpoint enters this block
            # Submissions are wrapped in `<item>` nodes.
            return dicttoxml(data, attr_type=False)

        if renderer_context.get("view").action == "list":
            return "<root>{}</root>".format("".join(data))
        else:
            return data 
Example #3
Source File: validation.py    From django-rest-registration with MIT License 5 votes vote down vote up
def validate_user_password_confirm(user_data: Dict[str, Any]) -> None:
    if user_data['password'] != user_data['password_confirm']:
        raise ValidationError(ErrorDetail(
            _("Passwords don't match"),
            code='passwords-do-not-match'),
        ) 
Example #4
Source File: errors.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, detail=None, code=None):
        if detail is None:
            detail = self.default_detail
        if code is None:
            code = self.default_code
        self.detail = ErrorDetail(detail, code) 
Example #5
Source File: test_update.py    From piclodio3 with MIT License 5 votes vote down vote up
def test_update_wrong_data_sent(self):
        data = {
            "active": "wrong",
            "webradio": 12,
        }
        response = self.client.post(self.url, data, format='json')
        expected = {'active': [ErrorDetail(string='Must be a valid boolean.', code='invalid')],
                    'webradio': [ErrorDetail(string='Invalid pk "12" - object does not exist.', code='does_not_exist')]}
        self.assertEquals(expected, response.data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #6
Source File: test_update.py    From piclodio3 with MIT License 5 votes vote down vote up
def test_update_web_radio_do_not_exist(self):
        data = {
            "active": True,
            "webradio": 12,
        }
        response = self.client.post(self.url, data, format='json')
        expected = {'webradio': [ErrorDetail(string='Invalid pk "12" - object does not exist.', code='does_not_exist')]}
        self.assertEquals(expected, response.data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #7
Source File: test_update.py    From piclodio3 with MIT License 5 votes vote down vote up
def test_set_volume_invalid(self):
        data = {
            "volume": 200
        }
        response = self.client.post(self.url, data, format='json')
        expected = {'volume':
                        [ErrorDetail(string='Ensure this value is less than or equal to 100.',
                                     code='max_value')]}
        self.assertEquals(expected, response.data)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example #8
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def errors(self):
        ret = super(Serializer, self).errors
        if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
            # Edge case. Provide a more descriptive error than
            # "this field may not be null", when no data is passed.
            detail = ErrorDetail('No data provided', code='null')
            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
        return ReturnDict(ret, serializer=self)


# There's some replication of `ListField` here,
# but that's probably better than obfuscating the call hierarchy. 
Example #9
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def errors(self):
        ret = super(ListSerializer, self).errors
        if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
            # Edge case. Provide a more descriptive error than
            # "this field may not be null", when no data is passed.
            detail = ErrorDetail('No data provided', code='null')
            ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
        if isinstance(ret, dict):
            return ReturnDict(ret, serializer=self)
        return ReturnList(ret, serializer=self)


# ModelSerializer & HyperlinkedModelSerializer
# -------------------------------------------- 
Example #10
Source File: fields.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_error_detail(exc_info):
    """
    Given a Django ValidationError, return a list of ErrorDetail,
    with the `code` populated.
    """
    code = getattr(exc_info, 'code', None) or 'invalid'
    return [
        ErrorDetail(msg, code=code)
        for msg in exc_info.messages
    ] 
Example #11
Source File: views.py    From swarfarm with Apache License 2.0 5 votes vote down vote up
def __init__(self, detail=None, code=None, reinit=True):
        message = detail if detail is not None else self.default_detail
        self.code = code if code is not None else self.default_code
        self.detail = {
            'detail': exceptions.ErrorDetail(message, self.default_code),
            'reinit': reinit,
        } 
Example #12
Source File: utils.py    From Django-Styleguide with MIT License 4 votes vote down vote up
def _get_list_of_errors(self, field_path='', errors_dict=None):
        """
        Error_dict is in the following format:
        {
            'field1': {
                'message': 'some message..'
                'code' 'some code...'
            },
            'field2: ...'
        }
        """
        if errors_dict is None:
            return []

        message_value = errors_dict.get(self.MESSAGE, None)

        # Note: If 'message' is name of a field we don't want to stop the recursion here!
        if message_value is not None and\
           (type(message_value) in {str, exceptions.ErrorDetail}):
            if field_path:
                errors_dict[self.FIELD] = field_path
            return [errors_dict]

        errors_list = []
        for key, value in errors_dict.items():
            new_field_path = '{0}.{1}'.format(field_path, key) if field_path else key
            key_is_non_field_errors = key == api_settings.NON_FIELD_ERRORS_KEY

            if type(value) is list:
                current_level_error_list = []
                new_value = value

                for error in new_value:
                    # if the type of field_error is list we need to unpack it
                    field_error = self._unpack(error)

                    if not key_is_non_field_errors:
                        field_error[self.FIELD] = new_field_path

                    current_level_error_list.append(field_error)
            else:
                path = field_path if key_is_non_field_errors else new_field_path

                current_level_error_list = self._get_list_of_errors(field_path=path, errors_dict=value)

            errors_list += current_level_error_list

        return errors_list