Python rest_framework.serializers.ValidationError() Examples

The following are 30 code examples of rest_framework.serializers.ValidationError(). 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.serializers , or try the search function .
Example #1
Source File: test_serializers.py    From normandy with Mozilla Public License 2.0 7 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 #2
Source File: serializers.py    From django-phone-verify with 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 #3
Source File: query_params.py    From koku with 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 #4
Source File: query_params.py    From koku with 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 #5
Source File: serializers.py    From koku with 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 #6
Source File: tests_query_params.py    From koku with 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 #7
Source File: filters.py    From normandy with 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 #8
Source File: filters.py    From normandy with 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 #9
Source File: rides.py    From cride-platzi with 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 #10
Source File: filters.py    From normandy with 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 #11
Source File: rides.py    From cride-platzi with 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 #12
Source File: filters.py    From normandy with 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 #13
Source File: views.py    From aws-workshop with 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 #14
Source File: test_models.py    From normandy with 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 #15
Source File: test_models.py    From normandy with 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 #16
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def validate_records(self, value):
        # `records` is usually allowed to be empty (for idempotent delete), except for POST requests which are intended
        # for RRset creation only. We use the fact that DRF generic views pass the request in the serializer context.
        request = self.context.get('request')
        if request and request.method == 'POST' and not value:
            raise serializers.ValidationError('This field must not be empty when using POST.')
        return value 
Example #17
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def validate_type(value):
        if value in models.RRset.DEAD_TYPES:
            raise serializers.ValidationError(f'The {value} RRset type is currently unsupported.')
        if value in models.RRset.RESTRICTED_TYPES:
            raise serializers.ValidationError(f'You cannot tinker with the {value} RRset.')
        if value.startswith('TYPE'):
            raise serializers.ValidationError('Generic type format is not supported.')
        return value 
Example #18
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def to_internal_value(self, data):
        if not isinstance(data, str):
            raise serializers.ValidationError('Must be a string.', code='must-be-a-string')
        return super().to_internal_value({'content': data}) 
Example #19
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def __call__(self, value):
        if isinstance(self.instance, Model) and value != getattr(self.instance, self.field_name):
            raise serializers.ValidationError(self.message, code='read-only-on-update') 
Example #20
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def validate(self, attrs):
        captcha = attrs['id']  # Note that this already is the Captcha object
        if not captcha.verify(attrs['solution']):
            raise serializers.ValidationError('CAPTCHA could not be validated. Please obtain a new one and try again.')

        return attrs 
Example #21
Source File: rides.py    From cride-platzi with MIT License 5 votes vote down vote up
def validate_current_time(self, data):
        """Verify ride have indeed started."""
        ride = self.context['view'].get_object()
        if data <= ride.departure_date:
            raise serializers.ValidationError('Ride has not started yet')
        return data 
Example #22
Source File: tests_query_params.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_constructor_invalid_uri(self):
        """Test that ValidationError is raised with an invalid uri."""
        fake_request = Mock(spec=HttpRequest, GET=Mock(urlencode=Mock(return_value=self.FAKE.paragraph())))
        fake_view = Mock(
            spec=ReportView,
            provider=self.FAKE.word(),
            query_handler=Mock(provider=self.FAKE.word()),
            report="tags",
            serializer=Mock,
            tag_handler=[],
        )
        with self.assertRaises(ValidationError):
            QueryParameters(fake_request, fake_view) 
Example #23
Source File: rest.py    From django-hashid-field with MIT License 5 votes vote down vote up
def to_internal_value(self, data):
        try:
            value = super().to_internal_value(data)
            return Hashid(value, hashids=self._hashids)
        except ValueError:
            raise serializers.ValidationError("Invalid int or Hashid string") 
Example #24
Source File: compat.py    From django-rest-messaging with ISC License 5 votes vote down vote up
def compat_serializer_check_is_valid(serializer):
    """ http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue """
    if DRFVLIST[0] >= 3:
        serializer.is_valid(raise_exception=True)
    else:
        if not serializer.is_valid():
            serializers.ValidationError('The serializer raises a validation error') 
Example #25
Source File: tests_query_params.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_tenant_invalid(self):
        """Test that get_tenant() raises ValidationError when user is invalid."""
        with self.assertRaises(ValidationError):
            get_tenant(None) 
Example #26
Source File: tests_query_params.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_tenant_no_user(self):
        """Test that get_tenant() raises ValidationError when user is missing."""
        user = Mock(customer=Mock(schema_name="acct10001"))
        with patch("api.query_params.Tenant.objects.get", side_effect=User.DoesNotExist):
            with self.assertRaises(ValidationError):
                get_tenant(user) 
Example #27
Source File: data.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def validate_process(self, process):
        """Check that process is active."""
        if not process.is_active:
            raise serializers.ValidationError(
                "Process {} is not active.".format(process)
            )
        return process 
Example #28
Source File: relation.py    From resolwe with Apache License 2.0 5 votes vote down vote up
def validate_partitions(self, partitions):
        """Raise validation error if list of partitions is empty."""
        if not partitions:
            raise serializers.ValidationError("List of partitions must not be empty.")

        return partitions 
Example #29
Source File: change_password.py    From django-rest-registration with MIT License 5 votes vote down vote up
def validate_old_password(self, old_password):
        user = self.context['request'].user
        if not user.check_password(old_password):
            raise serializers.ValidationError(_("Old password is not correct"))
        return old_password 
Example #30
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def validate_new_email(self, value):
        if value == self.context['request'].user.email:
            raise serializers.ValidationError('Email address unchanged.')
        return value