How can I override a DjangoModelFormMutation field type in graphene?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How can I remove a trailing newline?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?Determine the type of an object?How do I list all files of a directory?

Is it okay to use open source code to do an interview task?

Can a UA Lore Mastery wizard use the Spell Secrets or Alchemical Casting features to modify spells cast through wands or staffs?

What are the consequences for a developed nation to not accept any refugees?

Is it better in terms of durability to remove card+battery or to connect to charger/computer via USB-C?

Operator hats with simpler-wick package

Why AI became applicable only after Nvidia's chips were available?

Need a non-volatile memory IC with near unlimited read/write operations capability

Sum of even numbers N?

Why do people prefer metropolitan areas, considering monsters and villains?

Intern not wearing safety equipment; how could I have handled this differently?

Who goes first? Person disembarking bus or the bicycle?

Why the Cauchy Distribution is so useful?

VHDL: is there a way to create an entity into which constants can be passed?

Users forgetting to regenerate PDF before sending it

Did depressed people far more accurately estimate how many monsters they killed in a video game?

Did Rabbi Akiva accept arguments from ignorance?

Shrinking padding of node with label options

Why won't the U.S. sign a peace treaty with North Korea?

what is the relation of guitar chords to actual notes in the measure

Password Hashing Security Using Scrypt & Argon2

What was the nature of the known bugs in the Space Shuttle software?

My previous employer committed a severe violation of the law and is also being sued by me. How do I explain the situation to future employers?

What is the Last Digit in the Result of the given Expression?

How to convert diagonal matrix to rectangular matrix



How can I override a DjangoModelFormMutation field type in graphene?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How can I remove a trailing newline?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?Determine the type of an object?How do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I'm building a simple recipe storage application that uses the Graphene package for GraphQL. I've been able to use Django Forms so far very easily in my mutations, however one of my models fields is really an Enum and I'd like to expose it in Graphene/GraphQL as such.



My enum:



class Unit(Enum):
# Volume
TEASPOON = "teaspoon"
TABLESPOON = "tablespoon"
FLUID_OUNCE = "fl oz"
CUP = "cup"
US_PINT = "us pint"
IMPERIAL_PINT = "imperial pint"
US_QUART = "us quart"
IMPERIAL_QUART = "imperial quart"
US_GALLON = "us gallon"
IMPERIAL_GALLON = "imperial gallon"
MILLILITER = "milliliter"
LITER = "liter"

# Mass and Weight
POUND = "pound"
OUNCE = "ounce"
MILLIGRAM = "milligram"
GRAM = "gram"
KILOGRAM = "kilogram"


My Model:



class RecipeIngredient(TimeStampedModel):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients')

quantity = models.DecimalField(decimal_places=2, max_digits=10)
unit = models.TextField(choices=Unit.as_tuple_list())


My form:



class RecipeIngredientForm(forms.ModelForm):
class Meta:
model = RecipeIngredient
fields = (
'recipe',
'direction',
'quantity',
'unit',
)


My Mutation:



class CreateRecipeIngredientMutation(DjangoModelFormMutation):
class Meta:
form_class = RecipeIngredientForm
exclude_fields = ('id',)


I've created this graphene enum UnitEnum = Enum.from_enum(Unit) however I haven't been able to get graphene to pick it up. I've tried adding it to the CreateRecipeIngredientMutation as a regular field like unit = UnitEnum() as well as an Input class on that mutation. So far, the closest I've gotten is this Github issue from awhile ago. After playing around with the class in an iPython shell, I think I could just do CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum() but this feels awful.










share|improve this question




























    2















    I'm building a simple recipe storage application that uses the Graphene package for GraphQL. I've been able to use Django Forms so far very easily in my mutations, however one of my models fields is really an Enum and I'd like to expose it in Graphene/GraphQL as such.



    My enum:



    class Unit(Enum):
    # Volume
    TEASPOON = "teaspoon"
    TABLESPOON = "tablespoon"
    FLUID_OUNCE = "fl oz"
    CUP = "cup"
    US_PINT = "us pint"
    IMPERIAL_PINT = "imperial pint"
    US_QUART = "us quart"
    IMPERIAL_QUART = "imperial quart"
    US_GALLON = "us gallon"
    IMPERIAL_GALLON = "imperial gallon"
    MILLILITER = "milliliter"
    LITER = "liter"

    # Mass and Weight
    POUND = "pound"
    OUNCE = "ounce"
    MILLIGRAM = "milligram"
    GRAM = "gram"
    KILOGRAM = "kilogram"


    My Model:



    class RecipeIngredient(TimeStampedModel):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
    direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients')

    quantity = models.DecimalField(decimal_places=2, max_digits=10)
    unit = models.TextField(choices=Unit.as_tuple_list())


    My form:



    class RecipeIngredientForm(forms.ModelForm):
    class Meta:
    model = RecipeIngredient
    fields = (
    'recipe',
    'direction',
    'quantity',
    'unit',
    )


    My Mutation:



    class CreateRecipeIngredientMutation(DjangoModelFormMutation):
    class Meta:
    form_class = RecipeIngredientForm
    exclude_fields = ('id',)


    I've created this graphene enum UnitEnum = Enum.from_enum(Unit) however I haven't been able to get graphene to pick it up. I've tried adding it to the CreateRecipeIngredientMutation as a regular field like unit = UnitEnum() as well as an Input class on that mutation. So far, the closest I've gotten is this Github issue from awhile ago. After playing around with the class in an iPython shell, I think I could just do CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum() but this feels awful.










    share|improve this question
























      2












      2








      2








      I'm building a simple recipe storage application that uses the Graphene package for GraphQL. I've been able to use Django Forms so far very easily in my mutations, however one of my models fields is really an Enum and I'd like to expose it in Graphene/GraphQL as such.



      My enum:



      class Unit(Enum):
      # Volume
      TEASPOON = "teaspoon"
      TABLESPOON = "tablespoon"
      FLUID_OUNCE = "fl oz"
      CUP = "cup"
      US_PINT = "us pint"
      IMPERIAL_PINT = "imperial pint"
      US_QUART = "us quart"
      IMPERIAL_QUART = "imperial quart"
      US_GALLON = "us gallon"
      IMPERIAL_GALLON = "imperial gallon"
      MILLILITER = "milliliter"
      LITER = "liter"

      # Mass and Weight
      POUND = "pound"
      OUNCE = "ounce"
      MILLIGRAM = "milligram"
      GRAM = "gram"
      KILOGRAM = "kilogram"


      My Model:



      class RecipeIngredient(TimeStampedModel):
      recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
      direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients')

      quantity = models.DecimalField(decimal_places=2, max_digits=10)
      unit = models.TextField(choices=Unit.as_tuple_list())


      My form:



      class RecipeIngredientForm(forms.ModelForm):
      class Meta:
      model = RecipeIngredient
      fields = (
      'recipe',
      'direction',
      'quantity',
      'unit',
      )


      My Mutation:



      class CreateRecipeIngredientMutation(DjangoModelFormMutation):
      class Meta:
      form_class = RecipeIngredientForm
      exclude_fields = ('id',)


      I've created this graphene enum UnitEnum = Enum.from_enum(Unit) however I haven't been able to get graphene to pick it up. I've tried adding it to the CreateRecipeIngredientMutation as a regular field like unit = UnitEnum() as well as an Input class on that mutation. So far, the closest I've gotten is this Github issue from awhile ago. After playing around with the class in an iPython shell, I think I could just do CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum() but this feels awful.










      share|improve this question














      I'm building a simple recipe storage application that uses the Graphene package for GraphQL. I've been able to use Django Forms so far very easily in my mutations, however one of my models fields is really an Enum and I'd like to expose it in Graphene/GraphQL as such.



      My enum:



      class Unit(Enum):
      # Volume
      TEASPOON = "teaspoon"
      TABLESPOON = "tablespoon"
      FLUID_OUNCE = "fl oz"
      CUP = "cup"
      US_PINT = "us pint"
      IMPERIAL_PINT = "imperial pint"
      US_QUART = "us quart"
      IMPERIAL_QUART = "imperial quart"
      US_GALLON = "us gallon"
      IMPERIAL_GALLON = "imperial gallon"
      MILLILITER = "milliliter"
      LITER = "liter"

      # Mass and Weight
      POUND = "pound"
      OUNCE = "ounce"
      MILLIGRAM = "milligram"
      GRAM = "gram"
      KILOGRAM = "kilogram"


      My Model:



      class RecipeIngredient(TimeStampedModel):
      recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
      direction = models.ForeignKey(RecipeDirection, on_delete=models.CASCADE, null=True, related_name='ingredients')

      quantity = models.DecimalField(decimal_places=2, max_digits=10)
      unit = models.TextField(choices=Unit.as_tuple_list())


      My form:



      class RecipeIngredientForm(forms.ModelForm):
      class Meta:
      model = RecipeIngredient
      fields = (
      'recipe',
      'direction',
      'quantity',
      'unit',
      )


      My Mutation:



      class CreateRecipeIngredientMutation(DjangoModelFormMutation):
      class Meta:
      form_class = RecipeIngredientForm
      exclude_fields = ('id',)


      I've created this graphene enum UnitEnum = Enum.from_enum(Unit) however I haven't been able to get graphene to pick it up. I've tried adding it to the CreateRecipeIngredientMutation as a regular field like unit = UnitEnum() as well as an Input class on that mutation. So far, the closest I've gotten is this Github issue from awhile ago. After playing around with the class in an iPython shell, I think I could just do CreateRecipeIngredientMutation.Input.unit.type.of_type = UnitEnum() but this feels awful.







      python django graphql graphene-python






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 17 at 23:50









      EliEli

      3605 silver badges16 bronze badges




      3605 silver badges16 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          I came up with a solution that works but is not pretty. I used the https://github.com/hzdg/django-enumfields package to help with this.



          I created my own form field:



          class EnumChoiceField(enumfields.forms.EnumChoiceField):
          def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
          if isinstance(enum, six.string_types):
          self.enum = import_string(enum)
          else:
          self.enum = enum

          super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)


          And used it in my Django form. Then in my custom AppConfig I did this:



          class CoreAppConfig(AppConfig):
          name = 'myapp.core'

          def ready(self):
          registry = get_global_registry()

          @convert_form_field.register(EnumChoiceField)
          def convert_form_field_to_enum(field: EnumChoiceField):
          converted = registry.get_converted_field(field.enum)
          if converted is None:
          raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
          return converted(description=field.help_text, required=field.required)


          And finally in my schema:



          UnitEnum = Enum.from_enum(Unit)
          get_global_registry().register_converted_field(Unit, UnitEnum)


          I really don't like this, but couldn't think of a better way to handle this. I came across this idea when searching down another graphene django issue here https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036.



          I feel like there has to be a better way to do this.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55213100%2fhow-can-i-override-a-djangomodelformmutation-field-type-in-graphene%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I came up with a solution that works but is not pretty. I used the https://github.com/hzdg/django-enumfields package to help with this.



            I created my own form field:



            class EnumChoiceField(enumfields.forms.EnumChoiceField):
            def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
            if isinstance(enum, six.string_types):
            self.enum = import_string(enum)
            else:
            self.enum = enum

            super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)


            And used it in my Django form. Then in my custom AppConfig I did this:



            class CoreAppConfig(AppConfig):
            name = 'myapp.core'

            def ready(self):
            registry = get_global_registry()

            @convert_form_field.register(EnumChoiceField)
            def convert_form_field_to_enum(field: EnumChoiceField):
            converted = registry.get_converted_field(field.enum)
            if converted is None:
            raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
            return converted(description=field.help_text, required=field.required)


            And finally in my schema:



            UnitEnum = Enum.from_enum(Unit)
            get_global_registry().register_converted_field(Unit, UnitEnum)


            I really don't like this, but couldn't think of a better way to handle this. I came across this idea when searching down another graphene django issue here https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036.



            I feel like there has to be a better way to do this.






            share|improve this answer



























              0














              I came up with a solution that works but is not pretty. I used the https://github.com/hzdg/django-enumfields package to help with this.



              I created my own form field:



              class EnumChoiceField(enumfields.forms.EnumChoiceField):
              def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
              if isinstance(enum, six.string_types):
              self.enum = import_string(enum)
              else:
              self.enum = enum

              super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)


              And used it in my Django form. Then in my custom AppConfig I did this:



              class CoreAppConfig(AppConfig):
              name = 'myapp.core'

              def ready(self):
              registry = get_global_registry()

              @convert_form_field.register(EnumChoiceField)
              def convert_form_field_to_enum(field: EnumChoiceField):
              converted = registry.get_converted_field(field.enum)
              if converted is None:
              raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
              return converted(description=field.help_text, required=field.required)


              And finally in my schema:



              UnitEnum = Enum.from_enum(Unit)
              get_global_registry().register_converted_field(Unit, UnitEnum)


              I really don't like this, but couldn't think of a better way to handle this. I came across this idea when searching down another graphene django issue here https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036.



              I feel like there has to be a better way to do this.






              share|improve this answer

























                0












                0








                0







                I came up with a solution that works but is not pretty. I used the https://github.com/hzdg/django-enumfields package to help with this.



                I created my own form field:



                class EnumChoiceField(enumfields.forms.EnumChoiceField):
                def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
                if isinstance(enum, six.string_types):
                self.enum = import_string(enum)
                else:
                self.enum = enum

                super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)


                And used it in my Django form. Then in my custom AppConfig I did this:



                class CoreAppConfig(AppConfig):
                name = 'myapp.core'

                def ready(self):
                registry = get_global_registry()

                @convert_form_field.register(EnumChoiceField)
                def convert_form_field_to_enum(field: EnumChoiceField):
                converted = registry.get_converted_field(field.enum)
                if converted is None:
                raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
                return converted(description=field.help_text, required=field.required)


                And finally in my schema:



                UnitEnum = Enum.from_enum(Unit)
                get_global_registry().register_converted_field(Unit, UnitEnum)


                I really don't like this, but couldn't think of a better way to handle this. I came across this idea when searching down another graphene django issue here https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036.



                I feel like there has to be a better way to do this.






                share|improve this answer













                I came up with a solution that works but is not pretty. I used the https://github.com/hzdg/django-enumfields package to help with this.



                I created my own form field:



                class EnumChoiceField(enumfields.forms.EnumChoiceField):
                def __init__(self, enum, *, coerce=lambda val: val, empty_value='', **kwargs):
                if isinstance(enum, six.string_types):
                self.enum = import_string(enum)
                else:
                self.enum = enum

                super().__init__(coerce=coerce, empty_value=empty_value, **kwargs)


                And used it in my Django form. Then in my custom AppConfig I did this:



                class CoreAppConfig(AppConfig):
                name = 'myapp.core'

                def ready(self):
                registry = get_global_registry()

                @convert_form_field.register(EnumChoiceField)
                def convert_form_field_to_enum(field: EnumChoiceField):
                converted = registry.get_converted_field(field.enum)
                if converted is None:
                raise ImproperlyConfigured("Enum %r is not registered." % field.enum)
                return converted(description=field.help_text, required=field.required)


                And finally in my schema:



                UnitEnum = Enum.from_enum(Unit)
                get_global_registry().register_converted_field(Unit, UnitEnum)


                I really don't like this, but couldn't think of a better way to handle this. I came across this idea when searching down another graphene django issue here https://github.com/graphql-python/graphene-django/issues/481#issuecomment-412227036.



                I feel like there has to be a better way to do this.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 22:49









                EliEli

                3605 silver badges16 bronze badges




                3605 silver badges16 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid …


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55213100%2fhow-can-i-override-a-djangomodelformmutation-field-type-in-graphene%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?