Python rest_framework.serializers.CharField() Examples

The following are 30 code examples for showing how to use rest_framework.serializers.CharField(). 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: opencraft   Author: open-craft   File: serializers.py    License: 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 2
Project: drf-friendly-errors   Author: FutureMind   File: test_serializers.py    License: 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 3
Project: cadasta-platform   Author: Cadasta   File: serializers.py    License: 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 4
Project: graphene-django   Author: graphql-python   File: test_mutation.py    License: 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 5
Project: graphene-django   Author: graphql-python   File: test_mutation.py    License: 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 6
Project: scout_apm_python   Author: scoutapp   File: django_app.py    License: 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
Project: product-definition-center   Author: product-definition-center   File: tests.py    License: 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 8
Project: product-definition-center   Author: product-definition-center   File: tests.py    License: 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 9
Project: product-definition-center   Author: product-definition-center   File: tests.py    License: 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
Project: product-definition-center   Author: product-definition-center   File: tests.py    License: 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 11
Project: django-rest-framework-mongoengine   Author: umutbozkurt   File: test_validators.py    License: 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 12
Project: django-rest-framework-mongoengine   Author: umutbozkurt   File: test_validators.py    License: 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 13
Project: drf-schema-adapter   Author: drf-forms   File: test_unit.py    License: 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 14
Project: django-rest-registration   Author: apragacz   File: serializers.py    License: 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 15
Project: django-rest-registration   Author: apragacz   File: serializers.py    License: 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 16
Project: koku   Author: project-koku   File: serializers.py    License: 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 
Example 17
Project: koku   Author: project-koku   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize the BaseSerializer."""
        self.tag_keys = kwargs.pop("tag_keys", None)
        super().__init__(*args, **kwargs)

        if self.tag_keys is not None:
            fkwargs = {"child": serializers.CharField(), "required": False}
            self._init_tag_keys(StringOrListField, fkwargs=fkwargs)

        if self._opfields:
            add_operator_specified_fields(self.fields, self._opfields) 
Example 18
def test_invalid_item():
    """
    When given an invalid value the ListOrItemField validate method should raise a ValidationError.
    """
    field = ListOrItemField(child=CharField(max_length=5))
    with pytest.raises(ValidationError):
        field.to_internal_value('123456') 
Example 19
def test_list_value_invalid_items():
    """
    When given a list with an invalid value the ListOrItemField validate method should raise a
    ValidationError.
    """
    field = ListOrItemField(child=CharField(max_length=5))
    with pytest.raises(ValidationError):
        field.to_internal_value(['12345', '123456']) 
Example 20
Project: drf-compound-fields   Author: estebistec   File: test_listfield.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_validate_elements_valid():
    """
    When a ListField is given a list whose elements are valid for the item-field, then validate
    should not raise a ValidationError.
    """
    field = ListField(child=CharField(max_length=5))
    try:
        field.to_internal_value(["a", "b", "c"])
    except ValidationError:
        assert False, "ValidationError was raised" 
Example 21
Project: drf-compound-fields   Author: estebistec   File: test_listfield.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_validate_elements_invalid():
    """
    When a ListField is given a list containing elements that are invalid for the item-field, then
    validate should raise a ValidationError.
    """
    field = ListField(child=CharField(max_length=5))
    with pytest.raises(ValidationError):
        field.to_internal_value(["012345", "012345"]) 
Example 22
def test_validate_non_included_keys():
    """
    When a dict has invalid values for keys that are not specified in included_keys, it should not
    report errors for those keys.
    """
    field = PartialDictField(included_keys=['a'], child=CharField(max_length=5),
                             required=False)
    data = {'b': '123456'}
    try:
        field.to_internal_value(data)
    except ValidationError:
        assert False, 'Got a ValidationError for a non-included key' 
Example 23
Project: drf-compound-fields   Author: estebistec   File: test_dictfield.py    License: 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 24
Project: opencraft   Author: open-craft   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Add fields dynamically from the schema.
        """
        super().__init__(*args, **kwargs)
        static_content_overrides = {
            **static_content_overrides_v0_schema['properties']
        }

        for key, _ in static_content_overrides.items():
            if key == 'version':
                field_type = serializers.IntegerField(required=False)
            else:
                field_type = serializers.CharField(required=False, allow_blank=True)
            self.fields[key] = field_type 
Example 25
Project: rdmo   Author: rdmorganiser   File: serializers.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(TranslationSerializerMixin, self).__init__(*args, **kwargs)

        meta = getattr(self, 'Meta', None)
        if meta:
            for lang_code, lang_string, lang_field in get_languages():
                for field in meta.trans_fields:
                    field_name = '%s_%s' % (field, lang_field)
                    model_field = meta.model._meta.get_field(field_name)

                    self.fields['%s_%s' % (field, lang_code)] = serializers.CharField(
                        source=field_name,
                        required=not model_field.blank,
                        allow_null=model_field.null,
                        allow_blank=model_field.blank) 
Example 26
Project: djoser   Author: sunscrapers   File: serializers.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["re_password"] = serializers.CharField(
            style={"input_type": "password"}
        ) 
Example 27
Project: djoser   Author: sunscrapers   File: serializers.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = None
        self.fields[settings.LOGIN_FIELD] = serializers.CharField(required=False) 
Example 28
Project: djoser   Author: sunscrapers   File: serializers.py    License: MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["re_new_" + settings.LOGIN_FIELD] = serializers.CharField() 
Example 29
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_true_annotations_queryset(self):
        """
        Get FieldAnnotation queryset
        """
        true_ann_qs = self.get_initial_queryset(FieldAnnotation)

        # WARN: fields order makes sense here for list view
        true_ann_only_fields = [
            'status_id',
            'modified_by_id',
            'modified_date']

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        true_ann_qs_annotate = OrderedDict(
            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=F('status__name'),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(Q(assignee__first_name__isnull=False) & ~Q(assignee__first_name='') &
                                    Q(assignee__last_name__isnull=False) & ~Q(assignee__last_name=''),
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        # WARN: MUST HAVE the same
        # 1. fields number
        # 2. fields order
        # for FieldAnnotation and FieldAnnotationFalseMatch querysets to perform UNION !!!
        # so .values() and .annotate() applies THE SAME fields number and order
        true_ann_fields = self.common_fields + true_ann_only_fields
        true_ann_qs = true_ann_qs.values(*true_ann_fields).annotate(**true_ann_qs_annotate)

        return true_ann_qs 
Example 30
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_false_annotations_queryset(self):
        """
        Get FieldAnnotationFalseMatch queryset
        """
        false_ann_qs = self.get_initial_queryset(FieldAnnotationFalseMatch)

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        false_ann_qs = false_ann_qs.values(*self.common_fields).annotate(
            status_id=Value(FieldAnnotationStatus.rejected_status_pk(), output_field=IntegerField()),
            modified_by_id=Value(None, output_field=CharField()),
            modified_date=Value(None, output_field=DateField()),

            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=Value('Rejected', output_field=CharField()),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(assignee__first_name__isnull=False,
                                    assignee__last_name__isnull=False,
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        return false_ann_qs