当前位置: 首页>>代码示例>>Python>>正文


Python serializers.CharField方法代码示例

本文整理汇总了Python中rest_framework.serializers.CharField方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.CharField方法的具体用法?Python serializers.CharField怎么用?Python serializers.CharField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rest_framework.serializers的用法示例。


在下文中一共展示了serializers.CharField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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 
开发者ID:open-craft,项目名称:opencraft,代码行数:27,代码来源:serializers.py

示例2: test_char_field_error_content

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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') 
开发者ID:FutureMind,项目名称:drf-friendly-errors,代码行数:23,代码来源:test_serializers.py

示例3: validate

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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 
开发者ID:Cadasta,项目名称:cadasta-platform,代码行数:25,代码来源:serializers.py

示例4: test_write_only_field

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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" 
开发者ID:graphql-python,项目名称:graphene-django,代码行数:22,代码来源:test_mutation.py

示例5: test_read_only_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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" 
开发者ID:graphql-python,项目名称:graphene-django,代码行数:18,代码来源:test_mutation.py

示例6: drf_router

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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 
开发者ID:scoutapp,项目名称:scout_apm_python,代码行数:23,代码来源:django_app.py

示例7: test_describe_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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'}
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:20,代码来源:tests.py

示例8: test_describe_field_with_complex_default

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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'}}) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:20,代码来源:tests.py

示例9: test_describe_nested_serializer

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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'}
                }
            }
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:18,代码来源:tests.py

示例10: test_describe_nested_serializer_many

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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'}
                }]
            }
        }) 
开发者ID:product-definition-center,项目名称:product-definition-center,代码行数:18,代码来源:tests.py

示例11: test_repr

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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`
# ----------------------------------- 
开发者ID:umutbozkurt,项目名称:django-rest-framework-mongoengine,代码行数:21,代码来源:test_validators.py

示例12: test_validation_attrs

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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
                             )) 
开发者ID:drf-forms,项目名称:drf-schema-adapter,代码行数:22,代码来源:test_unit.py

示例13: get_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
def get_fields(self):
        fields = super().get_fields()
        if self.has_password_confirm_field():
            fields['password_confirm'] = serializers.CharField(write_only=True)
        return fields 
开发者ID:apragacz,项目名称:django-rest-registration,代码行数:7,代码来源:serializers.py

示例14: add_operator_specified_fields

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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 
开发者ID:project-koku,项目名称:koku,代码行数:13,代码来源:serializers.py

示例15: __init__

# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import CharField [as 别名]
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) 
开发者ID:project-koku,项目名称:koku,代码行数:13,代码来源:serializers.py


注:本文中的rest_framework.serializers.CharField方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。