From 9e007b962e2480e1619b5863ee52f4cd498f80c2 Mon Sep 17 00:00:00 2001 From: Olivia Rodriguez Valdes Date: Mon, 7 Jan 2019 09:03:37 -0500 Subject: [PATCH] Add converter to graphene_django --- graphene_django/forms/converter.py | 25 ++++++++++++++++++++++++- graphene_django/forms/mutation.py | 6 +++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/graphene_django/forms/converter.py b/graphene_django/forms/converter.py index 87180b2..07988f4 100644 --- a/graphene_django/forms/converter.py +++ b/graphene_django/forms/converter.py @@ -1,8 +1,10 @@ from django import forms from django.core.exceptions import ImproperlyConfigured -from graphene import ID, Boolean, Float, Int, List, String, UUID, Date, DateTime, Time +from graphene import ID, Boolean, Float, Int, List, String, UUID, Date, DateTime, Time, Enum +from graphene.utils.str_converters import to_camel_case +from graphene_django.converter import get_choices from .forms import GlobalIDFormField, GlobalIDMultipleChoiceField from ..utils import import_single_dispatch @@ -82,3 +84,24 @@ def convert_form_field_to_time(field): @convert_form_field.register(GlobalIDFormField) def convert_form_field_to_id(field): return ID(required=field.required) + + +@convert_form_field.register(forms.TypedChoiceField) +def convert_form_to_enum(field, name): + choices = getattr(field, 'choices', None) + name = to_camel_case(name) + choices = list(get_choices(choices)) + named_choices = [(c[0], c[1]) for c in choices] + named_choices_descriptions = {c[0]: c[2] for c in choices} + + class EnumWithDescriptionsType(object): + """Enum type definition""" + + @property + def description(self): + """Return field description""" + + return named_choices_descriptions[self.name] + + enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) + return enum(description=field.help_text, required=field.required) diff --git a/graphene_django/forms/mutation.py b/graphene_django/forms/mutation.py index 63ea089..c39b3c3 100644 --- a/graphene_django/forms/mutation.py +++ b/graphene_django/forms/mutation.py @@ -30,7 +30,11 @@ def fields_for_form(form, only_fields, exclude_fields): if is_not_in_only or is_excluded: continue - fields[name] = convert_form_field(field) + choices = getattr(field, 'choices', None) + if choices: + fields[name] = convert_form_field(field, field.label or name) + else: + fields[name] = convert_form_field(field) return fields