當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。