Search code examples
djangographene-django

Graphene/Django mutations return null


I created the following model in my django app:

class Post(models.Model):
    title = models.CharField(max_length=125, unique=True)
    slug_title = models.SlugField(max_length=255, unique=True)
    body = models.TextField()
    published_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    status = models.BooleanField(default=False)

    class Meta:
        ordering = ['-published_date']

    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        self.slug_title = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

I want to be able to use an API to do POST/GET requests later on, so I decided to use graphene-django. Everything is installed properly and working.

As per the tutorials, I created my schema.py file as follow:

# define schema
class PostType(DjangoObjectType):
    class Meta:
        model = Post
        fields = ('title', 'body', 'author', 'published_date', 'status', 'slug_title')

class UserType(DjangoObjectType):
    class Meta:
        model = get_user_model()

class PostInput(graphene.InputObjectType):
    title = graphene.String()
    slug_title = graphene.String()
    body = graphene.String()
    author = graphene.Int()
    published_date = graphene.DateTime()
    status=graphene.Boolean()

class CreatePost(graphene.Mutation):
    class Arguments:
        input = PostInput(required=True)

    post = graphene.Field(PostType)
    
    @classmethod
    def mutate(cls, root, info, input):
        post = Post()
        post.title = input.title
        post.slug_title = input.slug_title
        post.body = input.body
        post.author = input.author
        post.published_date = input.published_date
        post.status = input.status
        post.save()

        return CreatePost(post=post)

class Query(graphene.ObjectType):

    all_posts = graphene.List(PostType)
    author_by_username = graphene.Field(UserType, username=graphene.String())
    posts_by_author = graphene.List(PostType, username=graphene.String())
    posts_by_slug = graphene.List(PostType, slug=graphene.String())


    def resolve_all_posts(root, info):
        return Post.objects.all()
    
    def resolve_author_by_username(root, info, username):
        return User.objects.get(username=username)
    
    def resolve_posts_by_author(root, info, username):
        return Post.objects.filter(author__username=username)
    
    def resolve_posts_by_slug(root, info, slug):
        return Post.objects.filter(slug_title=slug)

class Mutation(graphene.ObjectType):
    create_post=CreatePost.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

The query part is working as expected, but my mutation section doesn't seem to be working. When I try to create a mutation, I get the below:

{
  "data": {
    "create_post": {
      "post": null
    }
  }
}

I created a quick test to see if any errors would output when I run the mutation, but everything seems ok there.

def test_mutation_1(self):
        response = self.query(
            '''
            mutation {
                createPost(input:{
                    title:"Test Title", 
                    body:"Test body", 
                    author:1, 
                    publishedDate:"2016-07-20T17:30:15+05:30", 
                    status:false
                })
                {
                    post {
                    title
                    }
                }
            }
            '''
        )

        self.assertResponseNoErrors(response)

I get no error messages.

Any help would be appreciated!


Solution

  • The error: errors=[GraphQLError('Cannot assign "1": "Post.author" must be a "User" instance.'

    The solution: Alter my CreatePost class to the following:

    post.author = User.objects.get(pk=input.author_id)
    

    Instead of:

    post.author = input.author_id