How to get Django Graphene ModelForm Mutation to apply

1.7k views Asked by At

I'm trying to make this mutation create a new record in the database. It returns code 200 but no change to the database plus it returns null. The documentation is not clear on this issue.(ModelForm vs mutate function)

Graphql response:

{
  "data": {
    "addSubjectMark": {
      "subjectMark": null,
      "errors": []
    }
  }
}

According to django-graphene documentation, I'm using DjangoModelForm to handle the input into the db.

My schema.py:

class SubjectMarkType(DjangoObjectType):
    id = graphene.ID(required=True)
    class Meta:
        model = SubjectMark

class AddSubjectMarkMutation(DjangoModelFormMutation):
    subject_mark = graphene.Field(SubjectMarkType)
    class Meta:
        form_class = ReportForm

class Mutation(graphene.ObjectType):
    add_subject_mark = AddSubjectMarkMutation.Field()
  1. Do I need to add a save method to the form?
  2. Do I need to use the mutate function?(Docs unclear)

Thanks!

1

There are 1 answers

0
William Osilaja Boampong On

The ReportForm should work as default with Django no modification is required. The missing piece is resolving the subject_mark attribute in the AddSubjectMarkMutation class.

class SubjectMarkType(DjangoObjectType):
    id = graphene.ID(required=True)

    class Meta:
        model = SubjectMark


class AddSubjectMarkMutation(DjangoModelFormMutation):
    subject_mark = graphene.Field(SubjectMarkType)

    class Meta:
        form_class = ReportForm  # NB. make sure ReportForm is able to save in Django

    # you need to resolve subject_mark to return the new object
    def resolve_subject_mark(self, info, **kwargs):
        return self.subjectMark


class Mutation(graphene.ObjectType):
    add_subject_mark = AddSubjectMarkMutation.Field()