Python rest_framework.serializers.ValidationError() Examples

The following are 30 code examples for showing how to use rest_framework.serializers.ValidationError(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .

Example 1
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def to_jexl(self):
        comparison = self.initial_data["comparison"]
        value = self.initial_data["value"]

        if comparison == "equal":
            operator = "=="
        elif comparison == "not_equal":
            operator = "!="
        elif comparison == "greater_than":
            operator = ">"
        elif comparison == "greater_than_equal":
            operator = ">="
        elif comparison == "less_than":
            operator = "<"
        elif comparison == "less_than_equal":
            operator = "<="
        else:
            raise serializers.ValidationError(f"Unrecognized comparison {comparison!r}")

        return f"{self.left_of_operator} {operator} {value}" 
Example 2
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def to_jexl(self):
        comparison = self.initial_data["comparison"]
        value = self.initial_data["value"]
        pref = self.initial_data["pref"]

        if comparison == "contains":
            return f"{json.dumps(value)} in '{pref}'|preferenceValue"
        if comparison == "equal":
            symbol = "=="
        elif comparison == "not_equal":
            symbol = "!="
        elif comparison == "greater_than":
            symbol = ">"
        elif comparison == "greater_than_equal":
            symbol = ">="
        elif comparison == "less_than":
            symbol = "<"
        elif comparison == "less_than_equal":
            symbol = "<="
        else:
            raise serializers.ValidationError(f"Unrecognized comparison {comparison!r}")

        return f"'{pref}'|preferenceValue {symbol} {json.dumps(value)}" 
Example 3
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def to_jexl(self):
        direction = self.initial_data["direction"]
        date = self.initial_data["date"]

        days = (datetime.strptime(date, "%Y-%M-%d") - datetime(1970, 1, 1)).days

        if direction == "olderThan":
            symbol = "<="
        elif direction == "newerThan":
            symbol = ">"
        else:
            raise serializers.ValidationError(f"Unrecognized direction {direction!r}")

        return "||".join(
            [
                "(!normandy.telemetry.main)",
                f"(normandy.telemetry.main.environment.profile.creationDate{symbol}{days})",
            ]
        ) 
Example 4
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def to_jexl(self):
        built_expression = "(" + self.initial_data["expression"] + ")"
        jexl = JEXL()

        # Add mock transforms for validation. See
        # https://mozilla.github.io/normandy/user/filters.html#transforms
        # for a list of what transforms we expect to be available.
        jexl.add_transform("date", lambda x: x)
        jexl.add_transform("stableSample", lambda x: x)
        jexl.add_transform("bucketSample", lambda x: x)
        jexl.add_transform("preferenceValue", lambda x: x)
        jexl.add_transform("preferenceIsUserSet", lambda x: x)
        jexl.add_transform("preferenceExists", lambda x: x)

        errors = list(jexl.validate(built_expression))
        if errors:
            raise serializers.ValidationError(errors)

        return built_expression 
Example 5
Project: normandy   Author: mozilla   File: test_serializers.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_validation_with_invalid_action(self):
        serializer = RecipeSerializer(
            data={"action_id": "action-that-doesnt-exist", "arguments": {}}
        )

        with pytest.raises(serializers.ValidationError):
            serializer.is_valid(raise_exception=True)

        assert serializer.errors["action_id"] == [
            serializers.PrimaryKeyRelatedField.default_error_messages["incorrect_type"].format(
                data_type="str"
            )
        ]

    # If the action specified cannot be found, raise validation
    # error indicating the arguments schema could not be loaded 
Example 6
Project: normandy   Author: mozilla   File: test_models.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_unique_experiment_slug_update_collision(self):
            action = ActionFactory(name="preference-experiment")
            arguments_a = PreferenceExperimentArgumentsFactory(
                slug="a", branches=[{"slug": "one"}]
            )
            arguments_b = PreferenceExperimentArgumentsFactory(
                slug="b", branches=[{"slug": "two"}]
            )
            # Does not throw when saving revisions
            RecipeFactory(action=action, arguments=arguments_a)
            recipe = RecipeFactory(action=action, arguments=arguments_b)

            with pytest.raises(serializers.ValidationError) as exc_info1:
                recipe.revise(arguments=arguments_a)
            error = action.errors["duplicate_experiment_slug"]
            assert exc_info1.value.detail == {"arguments": {"slug": error}} 
Example 7
Project: normandy   Author: mozilla   File: test_models.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_no_duplicates(self):
            action = ActionFactory(name="preference-rollout")
            arguments_a = {"slug": "a", "preferences": [{"preferenceName": "a", "value": "a"}]}
            arguments_b = {"slug": "b", "preferences": [{"preferenceName": "b", "value": "b"}]}
            RecipeFactory(action=action, arguments=arguments_a)
            recipe_b = RecipeFactory(action=action, arguments=arguments_b)
            expected_error = action.errors["duplicate_rollout_slug"]

            # Creating a new recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info1:
                RecipeFactory(action=action, arguments=arguments_a)
            assert exc_info1.value.detail == {"arguments": {"slug": expected_error}}

            # Revising an existing recipe fails
            with pytest.raises(serializers.ValidationError) as exc_info2:
                recipe_b.revise(arguments=arguments_a)
            assert exc_info2.value.detail == {"arguments": {"slug": expected_error}} 
Example 8
Project: django-phone-verify   Author: CuriousLearner   File: serializers.py    License: GNU General Public License v3.0 6 votes vote down vote up
def validate(self, attrs):
        attrs = super().validate(attrs)
        phone_number = attrs.get("phone_number", None)
        security_code, session_token = (
            attrs.get("security_code", None),
            attrs.get("session_token", None),
        )
        backend = get_sms_backend(phone_number=phone_number)
        verification, token_validatation = backend.validate_security_code(
            security_code=security_code,
            phone_number=phone_number,
            session_token=session_token,
        )

        if verification is None:
            raise serializers.ValidationError(_("Security code is not valid"))
        elif token_validatation == backend.SESSION_TOKEN_INVALID:
            raise serializers.ValidationError(_("Session Token mis-match"))
        elif token_validatation == backend.SECURITY_CODE_EXPIRED:
            raise serializers.ValidationError(_("Security code has expired"))
        elif token_validatation == backend.SECURITY_CODE_VERIFIED:
            raise serializers.ValidationError(_("Security code is already verified"))

        return attrs 
Example 9
Project: aws-workshop   Author: tryolabs   File: views.py    License: MIT License 6 votes vote down vote up
def post(self, request, username=None):
        follower = self.request.user.profile

        try:
            followee = Profile.objects.get(user__username=username)
        except Profile.DoesNotExist:
            raise NotFound('A profile with this username was not found.')

        if follower.pk is followee.pk:
            raise serializers.ValidationError('You can not follow yourself.')

        follower.follow(followee)

        serializer = self.serializer_class(followee, context={
            'request': request
        })

        return Response(serializer.data, status=status.HTTP_201_CREATED) 
Example 10
Project: cride-platzi   Author: pablotrinidad   File: rides.py    License: MIT License 6 votes vote down vote up
def validate(self, data):
        """Validate.

        Verify that the person who offers the ride is member
        and also the same user making the request.
        """
        if self.context['request'].user != data['offered_by']:
            raise serializers.ValidationError('Rides offered on behalf of others are not allowed.')

        user = data['offered_by']
        circle = self.context['circle']
        try:
            membership = Membership.objects.get(
                user=user,
                circle=circle,
                is_active=True
            )
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the circle.')

        if data['arrival_date'] <= data['departure_date']:
            raise serializers.ValidationError('Departure date must happen after arrival date.')

        self.context['membership'] = membership
        return data 
Example 11
Project: cride-platzi   Author: pablotrinidad   File: rides.py    License: MIT License 6 votes vote down vote up
def validate_passenger(self, data):
        """Verify passenger exists and is a circle member."""
        try:
            user = User.objects.get(pk=data)
        except User.DoesNotExist:
            raise serializers.ValidationError('Invalid passenger.')

        circle = self.context['circle']
        try:
            membership = Membership.objects.get(
                user=user,
                circle=circle,
                is_active=True
            )
        except Membership.DoesNotExist:
            raise serializers.ValidationError('User is not an active member of the circle.')

        self.context['user'] = user
        self.context['member'] = membership
        return data 
Example 12
Project: koku   Author: project-koku   File: query_params.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_providers(self, provider):
        """Get the providers.

        Return the appropriate provider and provider resource type from self.provider_resource_list

        """

        access = []
        provider_list = provider.split("_")
        if "all" in provider_list:
            for p, v in self.provider_resource_list.items():
                access.extend(v)
        else:
            for p in provider_list:
                if self.provider_resource_list.get(p) is None:
                    msg = f'Invalid provider "{p}".'
                    raise ValidationError({"details": _(msg)})
                access.extend(self.provider_resource_list[p])
        return access 
Example 13
Project: koku   Author: project-koku   File: query_params.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_tenant(user):
    """Get the tenant for the given user.

    Args:
        user    (DjangoUser): user to get the associated tenant
    Returns:
        (Tenant): Object used to get tenant specific data tables
    Raises:
        (ValidationError): If no tenant could be found for the user

    """
    tenant = None
    if user:
        try:
            customer = user.customer
            tenant = Tenant.objects.get(schema_name=customer.schema_name)
        except User.DoesNotExist:
            pass
    if tenant:
        return tenant
    raise ValidationError({"details": _("Invalid user definition")}) 
Example 14
Project: koku   Author: project-koku   File: serializers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_customer_from_context(self):
        """Get customer from context."""
        customer = self.context.get("customer")
        if customer:
            return customer
        else:
            request = self.context.get("request")
            if request and hasattr(request, "META"):
                _, json_rh_auth = extract_header(request, RH_IDENTITY_HEADER)
                if (
                    json_rh_auth
                    and "identity" in json_rh_auth
                    and "account_number" in json_rh_auth["identity"]  # noqa: W504
                ):
                    account = json_rh_auth["identity"]["account_number"]
                if account:
                    schema_name = create_schema_name(account)
                    customer = Customer.objects.get(schema_name=schema_name)
                else:
                    key = "customer"
                    message = "Customer for requesting user could not be found."
                    raise serializers.ValidationError(error_obj(key, message))
        return customer 
Example 15
Project: koku   Author: project-koku   File: tests_query_params.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_providers_with_nonsense_provider(self):
        """Test get providers raises validation error with nonsense provider."""
        fake_request = Mock(
            spec=HttpRequest,
            user=Mock(access=Mock(get=lambda key, default: default), customer=Mock(schema_name="acct10001")),
            GET=Mock(urlencode=Mock(return_value="")),
        )
        fake_view = Mock(
            spec=ReportView,
            provider=self.FAKE.word(),
            query_handler=Mock(provider=random.choice(PROVIDERS)),
            report=self.FAKE.word(),
            serializer=Mock,
            tag_handler=[],
        )
        params = QueryParameters(fake_request, fake_view)
        with self.assertRaises(ValidationError):
            params._get_providers("nonsense") 
Example 16
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    License: MIT License 5 votes vote down vote up
def is_valid(self, *args, **kwargs):
        valid = super(PolymorphicSerializer, self).is_valid(*args, **kwargs)
        try:
            resource_type = self._get_resource_type_from_mapping(self.validated_data)
            serializer = self._get_serializer_from_resource_type(resource_type)
        except serializers.ValidationError:
            child_valid = False
        else:
            child_valid = serializer.is_valid(*args, **kwargs)
            self._errors.update(serializer.errors)
        return valid and child_valid 
Example 17
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    License: MIT License 5 votes vote down vote up
def _get_resource_type_from_mapping(self, mapping):
        try:
            return mapping[self.resource_type_field_name]
        except KeyError:
            raise serializers.ValidationError({
                self.resource_type_field_name: 'This field is required',
            }) 
Example 18
Project: django-rest-polymorphic   Author: apirobot   File: serializers.py    License: MIT License 5 votes vote down vote up
def _get_serializer_from_resource_type(self, resource_type):
        try:
            model = self.resource_type_model_mapping[resource_type]
        except KeyError:
            raise serializers.ValidationError({
                self.resource_type_field_name: 'Invalid {0}'.format(
                    self.resource_type_field_name
                )
            })

        return self._get_serializer_from_model_or_instance(model) 
Example 19
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_procfile(self, data):
        for key, value in data.items():
            if value is None or value == "":
                raise serializers.ValidationError("Command can't be empty for process type")

            if not re.match(PROCTYPE_MATCH, key):
                raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)

        return data 
Example 20
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_memory(self, data):
        for key, value in data.items():
            if value is None:  # use NoneType to unset an item
                continue

            if not re.match(PROCTYPE_MATCH, key):
                raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)

            if not re.match(MEMLIMIT_MATCH, str(value)):
                raise serializers.ValidationError(
                    "Memory limit format: <number><unit> or <number><unit>/<number><unit>, "
                    "where unit = B, K, M or G")

        return data 
Example 21
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_cpu(self, data):
        for key, value in data.items():
            if value is None:  # use NoneType to unset an item
                continue

            if not re.match(PROCTYPE_MATCH, key):
                raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)

            shares = re.match(CPUSHARE_MATCH, str(value))
            if not shares:
                raise serializers.ValidationError(
                    "CPU limit format: <value> or <value>/<value>, where value must be a numeric")

        return data 
Example 22
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_tags(self, data):
        for key, value in data.items():
            if value is None:  # use NoneType to unset an item
                continue

            # split key into a prefix and name
            if '/' in key:
                prefix, name = key.split('/')
            else:
                prefix, name = None, key

            # validate optional prefix
            if prefix:
                if len(prefix) > 253:
                    raise serializers.ValidationError(
                        "Tag key prefixes must 253 characters or less.")

                for part in prefix.split('/'):
                    if not re.match(TAGVAL_MATCH, part):
                        raise serializers.ValidationError(
                            "Tag key prefixes must be DNS subdomains.")

            # validate required name
            if not re.match(TAGVAL_MATCH, name):
                raise serializers.ValidationError(
                    "Tag keys must be alphanumeric or \"-_.\", and 1-63 characters.")

            # validate value if it isn't empty
            if value and not re.match(TAGVAL_MATCH, str(value)):
                raise serializers.ValidationError(
                    "Tag values must be alphanumeric or \"-_.\", and 1-63 characters.")

        return data 
Example 23
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_healthcheck(self, data):
        for procType, healthcheck in data.items():
            if healthcheck is None:
                continue
            for key, value in healthcheck.items():
                if value is None:
                    continue
                if key not in ['livenessProbe', 'readinessProbe']:
                    raise serializers.ValidationError(
                        "Healthcheck keys must be either livenessProbe or readinessProbe")
                try:
                    jsonschema.validate(value, PROBE_SCHEMA)
                except jsonschema.ValidationError as e:
                    raise serializers.ValidationError(
                        "could not validate {}: {}".format(value, e.message))

            # http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_probe
            # liveness only supports successThreshold=1, no other value
            # This is not in the schema since readiness supports other values
            threshold = jmespath.search('livenessProbe.successThreshold', healthcheck)
            if threshold is not None and threshold != 1:
                raise serializers.ValidationError(
                    'livenessProbe successThreshold can only be 1'
                )

        return data 
Example 24
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_whitelist(self, data):
        for address in data:
            try:
                ipaddress.ip_address(address)
            except:
                try:
                    ipaddress.ip_network(address)
                except:
                    try:
                        ipaddress.ip_interface(address)
                    except:
                        raise serializers.ValidationError(
                           "The address {} is not valid".format(address))

        return data 
Example 25
Project: controller   Author: deis   File: serializers.py    License: MIT License 5 votes vote down vote up
def validate_autoscale(self, data):
        schema = {
            "$schema": "http://json-schema.org/schema#",
            "type": "object",
            "properties": {
                # minimum replicas autoscale will keep resource at based on load
                "min": {"type": "integer"},
                # maximum replicas autoscale will keep resource at based on load
                "max": {"type": "integer"},
                # how much CPU load there is to trigger scaling rules
                "cpu_percent": {"type": "integer"},
            },
            "required": ["min", "max", "cpu_percent"],
        }

        for proc, autoscale in data.items():
            if autoscale is None:
                continue

            try:
                jsonschema.validate(autoscale, schema)
            except jsonschema.ValidationError as e:
                raise serializers.ValidationError(
                    "could not validate {}: {}".format(autoscale, e.message)
                )

        return data 
Example 26
Project: normandy   Author: mozilla   File: serializers.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def validate_email(self, email):
        if User.objects.filter(email__iexact=email).exists():
            raise serializers.ValidationError({"email": "Already a user by that email."})
        return email 
Example 27
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def to_jexl(self):
        any_or_all = self.initial_data["any_or_all"]

        symbol = {"all": "&&", "any": "||"}.get(any_or_all)

        if not symbol:
            raise serializers.ValidationError(
                f"Unrecognized string for any_or_all: {any_or_all!r}"
            )

        return symbol.join(
            self.get_formatted_string(addon) for addon in self.initial_data["addons"]
        ) 
Example 28
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def validate_channels(self, value):
        # Avoid circular imports
        from normandy.recipes.models import Channel

        for slug in value:
            if not Channel.objects.filter(slug=slug).exists():
                raise serializers.ValidationError(f"Unrecognized channel slug {slug!r}")
        return value 
Example 29
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def validate_locales(self, value):
        # Avoid circular imports
        from normandy.recipes.models import Locale

        for code in value:
            if not Locale.objects.filter(code=code).exists():
                raise serializers.ValidationError(f"Unrecognized locale code {code!r}")
        return value 
Example 30
Project: normandy   Author: mozilla   File: filters.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def to_jexl(self):
        platforms_jexl = []
        for platform in self.initial_data["platforms"]:
            if platform == "all_mac":
                platforms_jexl.append("normandy.os.isMac")
            elif platform == "all_windows":
                platforms_jexl.append("normandy.os.isWindows")
            elif platform == "all_linux":
                platforms_jexl.append("normandy.os.isLinux")
            else:
                raise serializers.ValidationError(f"Unrecognized platform {platform!r}")

        return "||".join((p for p in platforms_jexl))