Python rest_framework.serializers.CharField() Examples

The following are 30 code examples of rest_framework.serializers.CharField(). 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: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_field_with_complex_default(self):
        class DummyDefault(object):
            doc_format = 'some string format'

        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(required=False, default=DummyDefault)

        instance = DummySerializer()
        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'field': {
                'tags': 'optional, default="some string format"',
                'value': 'string'
            }
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}}) 
Example #2
Source File: test_unit.py    From drf-schema-adapter with MIT License 6 votes vote down vote up
def test_validation_attrs(self):
        data = (
            (CharField(), {}),
            (IntegerField, {}),
            (CharField(min_length=3), {'min': 3}),
            (CharField(max_length=10), {'max': 10}),
            (CharField(min_length=3, max_length=10), {'min': 3, 'max': 10}),
            (IntegerField(min_value=0), {'min': 0}),
            (IntegerField(max_value=100), {'max': 100}),
            (IntegerField(min_value=0, max_value=100), {'min': 0, 'max': 100}),
        )

        for input_field, expected in data:
            result = utils.get_field_dict.get_validation_attrs(input_field)
            self.assertEqual(result, expected,
                             'got {} while expecting {} when comparing validation attrs for {}'.format(
                                 result,
                                 expected,
                                 input_field
                             )) 
Example #3
Source File: test_mutation.py    From graphene-django with MIT License 6 votes vote down vote up
def test_read_only_fields():
    class ReadOnlyFieldModelSerializer(serializers.ModelSerializer):
        cool_name = serializers.CharField(read_only=True)

        class Meta:
            model = MyFakeModelWithPassword
            fields = ["cool_name", "password"]

    class MyMutation(SerializerMutation):
        class Meta:
            serializer_class = ReadOnlyFieldModelSerializer

    assert "password" in MyMutation.Input._meta.fields
    assert (
        "cool_name" not in MyMutation.Input._meta.fields
    ), "'cool_name' is read_only field and shouldn't be on arguments" 
Example #4
Source File: test_validators.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_repr(self):
        class UniqueTogetherSerializer(DocumentSerializer):
            class Meta:
                model = UniqueTogetherModel
                fields = '__all__'

        serializer = UniqueTogetherSerializer()

        expected = dedent("""
            UniqueTogetherSerializer():
                id = ObjectIdField(read_only=True)
                name = CharField(required=True)
                code = IntegerField(required=True)
                class Meta:
                    validators = [<UniqueTogetherValidator(queryset=UniqueTogetherModel.objects, fields=('name', 'code'))>]
        """)
        assert repr(serializer) == expected 
Example #5
Source File: test_mutation.py    From graphene-django with MIT License 6 votes vote down vote up
def test_write_only_field():
    class WriteOnlyFieldModelSerializer(serializers.ModelSerializer):
        password = serializers.CharField(write_only=True)

        class Meta:
            model = MyFakeModelWithPassword
            fields = ["cool_name", "password"]

    class MyMutation(SerializerMutation):
        class Meta:
            serializer_class = WriteOnlyFieldModelSerializer

    result = MyMutation.mutate_and_get_payload(
        None, mock_info(), **{"cool_name": "New Narf", "password": "admin"}
    )

    assert hasattr(result, "cool_name")
    assert not hasattr(
        result, "password"
    ), "'password' is write_only field and shouldn't be visible" 
Example #6
Source File: django_app.py    From scout_apm_python with MIT License 6 votes vote down vote up
def drf_router():
    """
    DRF Router as a lazy object because it needs to import User model which
    can't be done until after django.setup()
    """
    from django.contrib.auth.models import User
    from rest_framework import routers
    from rest_framework import serializers
    from rest_framework import viewsets

    class UserSerializer(serializers.Serializer):
        id = serializers.IntegerField(label="ID", read_only=True)
        username = serializers.CharField(max_length=200)

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

    router = routers.SimpleRouter()
    router.register(r"users", UserViewSet)
    return router 
Example #7
Source File: test_validators.py    From django-rest-framework-mongoengine with MIT License 6 votes vote down vote up
def test_repr(self):
        class UniqueSerializer(DocumentSerializer):
            class Meta:
                model = UniqueValidatingModel
                fields = '__all__'

        serializer = UniqueSerializer()

        expected = dedent("""
            UniqueSerializer():
                id = ObjectIdField(read_only=True)
                name = CharField(required=True, validators=[<UniqueValidator(queryset=UniqueValidatingModel.objects)>])
                code = IntegerField(required=False)
        """)
        assert repr(serializer) == expected


# Tests for explicit `UniqueTogetherValidator`
# ----------------------------------- 
Example #8
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_fields(self):
        class DummySerializer(serializers.Serializer):
            str = serializers.CharField()
            int = serializers.IntegerField()

        instance = DummySerializer()

        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        }) 
Example #9
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_nested_serializer(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer()

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': {
                    'field': {'value': 'string'}
                }
            }
        }) 
Example #10
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def validate(self, data):
        data = super().validate(data)

        errors = {}

        for name, field in self.fields.items():
            if type(field) is serializers.CharField:
                value = data.get(name)
                if value:
                    value = value.strip()
                    data[name] = value
                valid = sanitize_string(value)
            elif type(field) is serializers.JSONField:
                value = data.get(name, {}) or {}
                valid = all(sanitize_string(value[k]) for k in value)

            if not valid:
                errors[name] = [SANITIZE_ERROR]

        if errors:
            raise serializers.ValidationError(errors)

        return data 
Example #11
Source File: serializers.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Start with empty serializer and add fields from both theme schemas
        """
        super().__init__(*args, **kwargs)

        # We're just going to use the v1 theme schema here since v0 is
        # getting deprecated soon
        theme_schema_combined = {
            **theme_schema_v1['properties']
        }
        for key, value in theme_schema_combined.items():
            field_type = None
            if key == 'version':
                field_type = serializers.IntegerField(required=False)
            elif value == ref('flag'):
                field_type = serializers.BooleanField(required=False)
            else:
                field_type = serializers.CharField(
                    max_length=7,
                    required=False,
                    allow_blank=True,
                    # TODO: Add a color validator here
                )
            self.fields[key] = field_type 
Example #12
Source File: test_serializers.py    From drf-friendly-errors with MIT License 6 votes vote down vote up
def test_char_field_error_content(self):
        # Too long string
        self.data_set['title'] = 'Too Long Title For Defined Serializer'
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['max_length']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # Empty string
        self.data_set['title'] = ''
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['blank']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title')

        # No data provided
        self.data_set.pop('title')
        s = run_is_valid(SnippetSerializer, data=self.data_set)
        code = settings.FRIENDLY_FIELD_ERRORS['CharField']['required']
        self.assertEqual(s.errors['errors'][0]['code'], code)
        self.assertEqual(s.errors['errors'][0]['field'], 'title') 
Example #13
Source File: tests.py    From product-definition-center with MIT License 6 votes vote down vote up
def test_describe_nested_serializer_many(self):
        class DummyNestedSerializer(serializers.Serializer):
            field = serializers.CharField()

        class DummySerializer(serializers.Serializer):
            top_level = DummyNestedSerializer(many=True)

        instance = DummySerializer()
        result = describe_serializer(instance, True)
        self.assertEqual(_flatten_field_data(result), {
            'top_level': {
                'value': [{
                    'field': {'value': 'string'}
                }]
            }
        }) 
Example #14
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_describe_read_only_field(self):
        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(read_only=True)

        instance = DummySerializer()

        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {})

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}}) 
Example #15
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_describe_nullable_field(self):
        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(allow_null=True)

        instance = DummySerializer()
        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'field': {'tags': 'nullable', 'value': 'string'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'tags': 'nullable', 'value': 'string'}}) 
Example #16
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_describe_read_only_field_can_be_excluded(self):
        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(read_only=True)

        instance = DummySerializer()
        result = describe_serializer(instance, False)
        self.assertEqual(result, {}) 
Example #17
Source File: test_field_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_list_convert_to_list():
    class StringListField(serializers.ListField):
        child = serializers.CharField()

    field_a = assert_conversion(
        serializers.ListField,
        graphene.List,
        child=serializers.IntegerField(min_value=0, max_value=100),
    )

    assert field_a.of_type == graphene.Int

    field_b = assert_conversion(StringListField, graphene.List)

    assert field_b.of_type == graphene.String 
Example #18
Source File: serializers.py    From drf-haystack with MIT License 5 votes vote down vote up
def get_text(self, instance):
        """
        Haystack facets are returned as a two-tuple (value, count).
        The text field should contain the faceted value.
        """
        instance = instance[0]
        if isinstance(instance, (six.text_type, six.string_types)):
            return serializers.CharField(read_only=True).to_representation(instance)
        elif isinstance(instance, datetime):
            return serializers.DateTimeField(read_only=True).to_representation(instance)
        return instance 
Example #19
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def test_describe_field_with_default_value(self):
        class DummySerializer(serializers.Serializer):
            field = serializers.CharField(required=False, default='foo')

        instance = DummySerializer()
        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'field': {'tags': 'optional, default="foo"', 'value': 'string'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {'field': {'value': 'string'}}) 
Example #20
Source File: tests.py    From product-definition-center with MIT License 5 votes vote down vote up
def setUp(self):

        class DummySerializer(serializers.Serializer):
            nickname = serializers.CharField()
            color = serializers.CharField()

            def create(self, validated_data):
                return mock.Mock(pk=2, **validated_data)

            def update(self, obj, validated_data):
                return mock.Mock(pk=obj.pk, **validated_data)

        class GetDogMixin(object):
            def get_object(self):
                return mock.Mock(pk=1, nickname='Spot', color='black')

        class DummyView(viewsets.NotificationMixin,
                        mixins.CreateModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        GetDogMixin,
                        GenericViewSet):
            serializer_class = DummySerializer

        mapping = {
            'post': 'create',
            'put': 'update',
            'delete': 'destroy',
        }
        self.view = DummyView.as_view(mapping, basename='dummy') 
Example #21
Source File: serializers.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def __new__(cls, name, bases, attrs):
        ansible_reference = attrs.get('ansible_reference', None)
        if ansible_reference and name != '_AnsibleSerializer':
            ansible_type = None
            if isinstance(attrs.get('playbook', None), serializers.CharField):
                ansible_type = 'playbook'
            elif isinstance(attrs.get('module', None), serializers.CharField):
                ansible_type = 'module'
            attrs.update(generate_fileds(attrs['ansible_reference'], ansible_type))
        return super(AnsibleSerializerMetaclass, cls).__new__(cls, name, bases, attrs) 
Example #22
Source File: test_drf.py    From pydantic with MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        class Model(serializers.Serializer):
            id = serializers.IntegerField()
            client_name = serializers.CharField(max_length=255, trim_whitespace=False)
            sort_index = serializers.FloatField()
            # client_email = serializers.EmailField(required=False, allow_null=True)
            client_phone = serializers.CharField(max_length=255, trim_whitespace=False, required=False, allow_null=True)

            class Location(serializers.Serializer):
                latitude = serializers.FloatField(required=False, allow_null=True)
                longitude = serializers.FloatField(required=False, allow_null=True)
            location = Location(required=False, allow_null=True)

            contractor = serializers.IntegerField(required=False, allow_null=True, min_value=0)
            upstream_http_referrer = serializers.CharField(
                max_length=1023, trim_whitespace=False, required=False, allow_null=True
            )
            grecaptcha_response = serializers.CharField(min_length=20, max_length=1000, trim_whitespace=False)
            last_updated = serializers.DateTimeField(required=False, allow_null=True)

            class Skill(serializers.Serializer):
                subject = serializers.CharField()
                subject_id = serializers.IntegerField()
                category = serializers.CharField()
                qual_level = serializers.CharField()
                qual_level_id = serializers.IntegerField()
                qual_level_ranking = serializers.FloatField(default=0)
            skills = serializers.ListField(child=Skill())

        self.allow_extra = allow_extra  # unused
        self.serializer = Model 
Example #23
Source File: test_validators.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_repr(self):
        serializer = UniqueValidatorSerializer()
        expected = dedent("""
            UniqueValidatorSerializer():
                id = ObjectIdField(read_only=True)
                name = CharField(validators=[<UniqueValidator(queryset=NonValidatingModel.objects)>])
                code = IntegerField(required=False)
        """)
        assert repr(serializer) == expected 
Example #24
Source File: test_validators.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_repr(self):
        serializer = UniqueTogetherValidatorSerializer()
        expected = dedent("""
            UniqueTogetherValidatorSerializer():
                id = ObjectIdField(read_only=True)
                name = CharField(required=False)
                code = IntegerField(required=False)
                class Meta:
                    validators = [<UniqueTogetherValidator(queryset=NonValidatingModel.objects, fields=('name', 'code'))>]
        """)
        assert repr(serializer) == expected 
Example #25
Source File: test_validators.py    From django-rest-framework-mongoengine with MIT License 5 votes vote down vote up
def test_repr_null(self):
        serializer = NullUniqueTogetherValidatorSerializer()
        expected = dedent("""
            NullUniqueTogetherValidatorSerializer():
                id = ObjectIdField(read_only=True)
                name = CharField(required=False)
                code = IntegerField(allow_null=True, required=False)
                other = CharField(allow_blank=True, allow_null=True, required=False)
                class Meta:
                    validators = [<UniqueTogetherValidator(queryset=NullValidatingModel.objects, fields=('name', 'code'))>]
        """)
        assert repr(serializer) == expected 
Example #26
Source File: test_mutation.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def test_mutation_mutate_and_get_payload_without_model(info):
    class MySerializer(Serializer):
        name = CharField()

        def create(self, validated_data):
            return validated_data

    class NoModelMutation(mutation.Mutation):
        class Meta:
            return_field_name = "test"
            serializer_class = MySerializer

    result = NoModelMutation.mutate_and_get_payload(None, info, name="test")
    assert type(result) == NoModelMutation 
Example #27
Source File: serializers.py    From django-rest-registration with MIT License 5 votes vote down vote up
def get_fields(self):
        fields = super().get_fields()
        if self.has_password_confirm_field():
            fields['password_confirm'] = serializers.CharField(write_only=True)
        return fields 
Example #28
Source File: test_dictfield.py    From drf-compound-fields with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_validate_elements_invalid():
    """
    When a DictField is given a dict containing values that are invalid for the value-field, then
    validate should raise a ValidationError.
    """
    field = DictField(child=CharField(max_length=5))
    with pytest.raises(ValidationError):
        field.to_internal_value({"a": "012345", "b": "012345"}) 
Example #29
Source File: serializers.py    From django-rest-registration with MIT License 5 votes vote down vote up
def get_fields(self):
        fields = super().get_fields()
        if registration_settings.SEND_RESET_PASSWORD_LINK_SERIALIZER_USE_EMAIL:
            fields['email'] = serializers.CharField(required=True)
        else:
            fields['login'] = serializers.CharField(required=True)
        return fields 
Example #30
Source File: serializers.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_operator_specified_fields(fields, field_list):
    """Add the specified and: and or: fields to the serialzer."""
    and_fields = {
        "and:" + field: StringOrListField(child=serializers.CharField(), required=False) for field in field_list
    }
    or_fields = {
        "or:" + field: StringOrListField(child=serializers.CharField(), required=False) for field in field_list
    }
    fields.update(and_fields)
    fields.update(or_fields)
    return fields