Search code examples
djangographqlstrawberry-graphql

Django Strawberry Graphql Bad request 'str' object has no attribute 'execute_sync'


So I have a simple django model

class County(models.Model):
    '''County'''
    name = models.CharField(max_length=100, null=False, blank=False)
    class Meta:
        verbose_name_plural = "Counties"
        ordering = ['name']

    def __str__(self):
        return self.name

here is my types.py

import strawberry
from strawberry.django import auto
from . import models

@strawberry.django.type(models.County)
class County:
    id: auto
    name: auto

and my schema.py

import strawberry
from .types import *

@strawberry.type
class Query:
    county: County = strawberry.django.field()
    counties: List[County] = strawberry.django.field()

schema = strawberry.Schema(query=Query)

For url.py"

from main.schema import schema
from strawberry.django.views import GraphQLView


urlpatterns = [
    path('admin/', admin.site.urls),
    path('graphql', GraphQLView.as_view(schema='schema'), name='graphql'),
]

Running the terminal gives me:

Unable to parse request body as JSON
Bad Request: /graphql
[08/Jan/2022 03:28:08] "GET /graphql HTTP/1.1" 400 113111

When I go into the graphql terminal at http://localhost:8000/graphql there is no documentation in the documentation explorer. If I type a query like:

{
  counties{
    id
    name
  }
}

I get this:

Internal Server Error: /graphql
Traceback (most recent call last):
  File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\00\Envs\eagle\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\00\Envs\eagle\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\00\Envs\eagle\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\00\Envs\eagle\lib\site-packages\strawberry\django\views.py", line 148, in dispatch
    result = self.schema.execute_sync(
AttributeError: 'str' object has no attribute 'execute_sync'
[08/Jan/2022 03:29:21] "POST /graphql HTTP/1.1" 500 16621

Solution

  • As @IainShelvington said in comments the parameter to GraphQLView should be a schema object you can also see it in docs:

     path('graphql', GraphQLView.as_view(schema=schema), name='graphql'),