Python rest_framework.serializers.ChoiceField() Examples

The following are 6 code examples of rest_framework.serializers.ChoiceField(). 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: serializers.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """Initialize the OrderSerializer."""
        super().__init__(*args, **kwargs)

        if self.tag_keys is not None:
            fkwargs = {"choices": OrderSerializer.ORDER_CHOICES, "required": False}
            self._init_tag_keys(serializers.ChoiceField, fkwargs=fkwargs) 
Example #2
Source File: serializer_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def convert_serializer_field(field, is_input=True, convert_choices_to_enum=True):
    """
    Converts a django rest frameworks field to a graphql field
    and marks the field as required if we are creating an input type
    and the field itself is required
    """

    if isinstance(field, serializers.ChoiceField) and not convert_choices_to_enum:
        graphql_type = graphene.String
    else:
        graphql_type = get_graphene_type_from_serializer_field(field)

    args = []
    kwargs = {"description": field.help_text, "required": is_input and field.required}

    # if it is a tuple or a list it means that we are returning
    # the graphql type and the child type
    if isinstance(graphql_type, (list, tuple)):
        kwargs["of_type"] = graphql_type[1]
        graphql_type = graphql_type[0]

    if isinstance(field, serializers.ModelSerializer):
        if is_input:
            graphql_type = convert_serializer_to_input_type(field.__class__)
        else:
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]
    elif isinstance(field, serializers.ListSerializer):
        field = field.child
        if is_input:
            kwargs["of_type"] = convert_serializer_to_input_type(field.__class__)
        else:
            del kwargs["of_type"]
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]

    return graphql_type(*args, **kwargs) 
Example #3
Source File: test_field_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_choice_convert_enum():
    field = assert_conversion(
        serializers.ChoiceField,
        graphene.Enum,
        choices=[("h", "Hello"), ("w", "World")],
        source="word",
    )
    assert field._meta.enum.__members__["H"].value == "h"
    assert field._meta.enum.__members__["H"].description == "Hello"
    assert field._meta.enum.__members__["W"].value == "w"
    assert field._meta.enum.__members__["W"].description == "World" 
Example #4
Source File: test_field_converter.py    From graphene-django with MIT License 5 votes vote down vote up
def test_should_choice_convert_string_if_enum_disabled():
    assert_conversion(
        serializers.ChoiceField,
        graphene.String,
        choices=[("h", "Hello"), ("w", "World")],
        source="word",
        convert_choices_to_enum=False,
    ) 
Example #5
Source File: REST_serializers.py    From YaraGuardian with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(YaraRuleSerializer, self).__init__(*args, **kwargs)

        try:
            source_blank = not self.retrieve_request_group().groupmeta.source_required
            self.fields['source'] = serializers.ChoiceField(choices=self.retrieve_sources(),
                                                            allow_blank=source_blank)

            category_blank = not self.retrieve_request_group().groupmeta.category_required
            self.fields['category'] = serializers.ChoiceField(choices=self.retrieve_categories(),
                                                              allow_blank=category_blank)

            self.fields['rule_content'].required = True

        except AttributeError:
            pass 
Example #6
Source File: residential_information.py    From omniport-backend with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Add the residence ChoiceField on the serializer based on the existence
        of Residence models
        :param args: arguments
        :param kwargs: keyword arguments
        """

        super().__init__(*args, **kwargs)

        try:
            residences = Residence.objects.all()
        except ProgrammingError:
            residences = list()

        self.fields['residence'] = serializers.ChoiceField(
            choices=[
                (residence.id, residence.name)
                for residence in residences
            ],
            write_only=True,
        )