I was following this tutorial to integrate Graphql with Django, I did everything according to that tutorial when I'm hitting graphql URL on my local machine
http://localhost:8000/graphql
I'm geting the following error
AssertionError at /graphql
A Schema is required to be provided to GraphQLView.
Request Method: GET
Request URL: http://localhost:8000/graphql
Django Version: 1.11.1
Exception Type: AssertionError
Exception Value:
A Schema is required to be provided to GraphQLView.
Exception Location: /home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages/graphene_django/views.py in init, line 84
Python Executable: /home/psingh/Projects/django_graphql/env/bin/python
Python Version: 2.7.6
Python Path:
['/home/psingh/Projects/django_graphql/project',
'/home/psingh/Projects/django_graphql/env/lib/python2.7',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/plat-x86_64-linux-gnu',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-old',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/psingh/Projects/django_graphql/env/local/lib/python2.7/site-packages',
'/home/psingh/Projects/django_graphql/env/lib/python2.7/site-packages']
Server time: Fri, 12 May 2017 12:18:31 +0000
In settings.py
GRAPHENE = {
'SCHEMA': 'project.schema.schema'
}
project> schema.py
import graphene
import mainapp.schema
class Query(mainapp.schema.Query, graphene.ObjectType):
# This class will inherit from multiple Queries
# as we begin to add more apps to our project
pass
schema = graphene.Schema(query=Query)
app>schema.py
import graphene
from graphene_django.types import DjangoObjectType
from cookbook.ingredients.models import Category, Ingredient
class CategoryType(DjangoObjectType):
class Meta:
model = Category
class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
class Query(graphene.AbstractType):
all_categories = graphene.List(CategoryType)
all_ingredients = graphene.List(IngredientType)
def resolve_all_categories(self, args, context, info):
return Category.objects.all()
def resolve_all_ingredients(self, args, context, info):
# We can easily optimize query count in the resolve method
return Ingredient.objects.select_related('category').all()
project_urls.py
from django.conf.urls import include, url
from django.contrib import admin
from graphene_django.views import GraphQLView
import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True)),
url(r'^', include('mainapp.urls')),
]
Any help would be great.I am new to the coding stuff.
Thanks in advance.
You have to add the schema to your settings.py as seen here:
GRAPHENE = {
'SCHEMA': 'cookbook.schema.schema'
}
You need 2 schema.py files, one at the root level of the project and one in the app folder.
if you don't want to add GRAPHENE variable in settings.py then you can pass scheme parameter in GraphQLView.as_view() method call
from onlineshop_project.scheme import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql', GraphQLView.as_view(graphiql=True, schema=schema)),
]
You can check the documentation.
Have you added "graphene_django" in INSTALLED_APPS under settings.py file ?
Check here - https://docs.graphene-python.org/projects/django/en/latest/tutorial-plain/#update-settings
Related
Trying a simple request:
urls.py
from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from django.http import HttpResponse
from rest_framework.urlpatterns import format_suffix_patterns
from .public_views import NavigationBar
router = routers.DefaultRouter()
router.register(r'navbar', NavigationBar, basename="NavigationBar")
urlpatterns = [
path('', include(router.urls))
]
urlpatterns = format_suffix_patterns(urlpatterns)
public_views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import api_view, throttle_classes
from . view_utils import *
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
class NavigationBar(APIView):
"""
obtain up to date navigation bar (or side menu navigation) hierarchy.
"""
permission_classes = ([AllowAny])
def get(self, request, format=None):
"""
get user addresses
"""
return Response("this is a good response")
def get_extra_actions(cls):
return []
When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error:
AttributeError at /v1/navbar
type object 'NavigationBar' has no attribute 'get_extra_actions'
Request Method: GET
Request URL: http://web/v1/navbar
Django Version: 2.1
Exception Type: AttributeError
Exception Value:
type object 'NavigationBar' has no attribute 'get_extra_actions'
Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.6.8
Python Path:
['.',
'',
'/usr/local/lib/python36.zip',
'/usr/local/lib/python3.6',
'/usr/local/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/site-packages']
Server time: Tue, 2 Jul 2019 17:12:27 +0000
I would appreciate any pointers. Also, I fail to understand why the error message includes a Request URL: http://web/v1/navbar indication when web is not part of the URL I'm using. Where is web coming from??? I just use /v1/navbar/ to hit the endpoint.
There are two things wrong here. First, routers are for viewsets, not simple views. Secondly, with a class based view you need to call it via its as_view() method in the urlconf. So get rid of that router stuff and just do:
urlpatterns = [
path(r'navbar', NavigationBar.as_view(), name="NavigationBar")
]
Note, now you're not using a router, you don't need that get_extra_actions method at all.
Trying a simple request:
urls.py
from django.conf.urls import url
from django.urls import include, path
from rest_framework import routers
from django.http import HttpResponse
from rest_framework.urlpatterns import format_suffix_patterns
from .public_views import NavigationBar
router = routers.DefaultRouter()
router.register(r'navbar', NavigationBar, basename="NavigationBar")
urlpatterns = [
path('', include(router.urls))
]
urlpatterns = format_suffix_patterns(urlpatterns)
public_views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.throttling import UserRateThrottle
from rest_framework.decorators import api_view, throttle_classes
from . view_utils import *
class OncePerDayUserThrottle(UserRateThrottle):
rate = '1/day'
class NavigationBar(APIView):
"""
obtain up to date navigation bar (or side menu navigation) hierarchy.
"""
permission_classes = ([AllowAny])
def get(self, request, format=None):
"""
get user addresses
"""
return Response("this is a good response")
def get_extra_actions(cls):
return []
When I API call the /v1/navbar or /v1/navbar/ endpoints (I do have my main urls.py lead all /v1/ traffic to another dedicated urls.py), I am getting the following error:
AttributeError at /v1/navbar
type object 'NavigationBar' has no attribute 'get_extra_actions'
Request Method: GET
Request URL: http://web/v1/navbar
Django Version: 2.1
Exception Type: AttributeError
Exception Value:
type object 'NavigationBar' has no attribute 'get_extra_actions'
Exception Location: /usr/local/lib/python3.6/site-packages/rest_framework/routers.py in get_routes, line 200
Python Executable: /usr/local/bin/uwsgi
Python Version: 3.6.8
Python Path:
['.',
'',
'/usr/local/lib/python36.zip',
'/usr/local/lib/python3.6',
'/usr/local/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/site-packages']
Server time: Tue, 2 Jul 2019 17:12:27 +0000
I would appreciate any pointers. Also, I fail to understand why the error message includes a Request URL: http://web/v1/navbar indication when web is not part of the URL I'm using. Where is web coming from??? I just use /v1/navbar/ to hit the endpoint.
There are two things wrong here. First, routers are for viewsets, not simple views. Secondly, with a class based view you need to call it via its as_view() method in the urlconf. So get rid of that router stuff and just do:
urlpatterns = [
path(r'navbar', NavigationBar.as_view(), name="NavigationBar")
]
Note, now you're not using a router, you don't need that get_extra_actions method at all.
Currently using a REST API and the generic views CreateUpdateDestroy, and my admin display GUI looks like this :
All the sources online that I've followed, tutorials etc get a generic view which looks much nicer.
Here is my views.py:
from rest_framework import generics
from models import Results
from serializers import ResulutsSerializer
class ResultsList(generics.ListAPIView):
queryset = Results.objects.all()
serializer_class = ResultsSerializer
class ResultsDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Results.objects.all()
serializer_class = ResultsSerializer
and urls.py:
from django.urls import path
from main import views
urlpatterns = [
path('results/', views.ResultsList.as_view()),
path('<int:pk>/', views.ResultsDetails.as_view())
]
what am I doing wrong?
It looks like you need to collect your app assets:
$ python manage.py collectstatic
# You can provide option: --settings=<your-settings-file> if you're using custom settings which is not default in manage.py
You will need to configure staticfiles settings in your Django settings module if not already configured – e.g. settings.py. Please follow documentation at:
https://docs.djangoproject.com/en/2.0/howto/static-files/
https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/
If you are developing locally:
You should set DEBUG=True in your Django Settings Module (i.e. normally settings.py)
I have a django project with three apps: website, blog, and customauth. The customauth app implements a custom user and AdminSite. The blog app has a Post model. I am trying to register the Post model with the custom AdminSite and I receive the following error:
NoReverseMatch at /my_admin/
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/my_admin/
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']
Here is customauth/admin.py:
class MyAdminSite(admin.AdminSite):
site_title = "Custom Administration Area"
site_header = 'Custom Administration Area'
def get_urls(self):
urls = super(MyAdminSite, self).get_urls()
my_urls = [
url(r'^my_view/$', self.my_view, name='my_view'),
]
return my_urls + urls
def my_view(self,request):
value = "You're looking at the new admin view."
context = dict(
# Include common variables for rendering the admin template.
self.each_context(request),
# Anything else you want in the context...
key=value,
)
return TemplateResponse(request, "website/admin.html", context)
admin_site = MyAdminSite(name='myadmin')
# Now register the new UserAdmin...
admin_site.register(MyUser, UserAdmin)
And here is blog/admin.py:
from django.contrib import admin
from customauth.admin import admin_site
# Register your models here.
from .models import Post
class PostAdmin(admin.ModelAdmin):
pass
admin_site.register(Post,PostAdmin)
Here is the website/urls.py:
from django.contrib import admin
from django.urls import include, path
from customauth.admin import admin_site
from . import views
urlpatterns = [
path('admin/', admin.site.urls, name='admin'),
path('my_admin/', include('customauth.urls'), name='custom_admin'),
path('', views.index, name='index'),
path('latest_news/', include('blog.urls'), name='latest_news')
]
And here is the customauth/urls.py:
from . import views
from .admin import admin_site
urlpatterns = [
path('', admin_site.my_view, name='custom_admin'),
]
What am I doing wrong?
I figured out what I did wrong.
The problem is the way I configured the urls.
In website.urls I changed:
path('my_admin/', include('customauth.urls'), name='custom_admin'),
to
path('my_admin/', admin_site.urls, name='custom_admin'),
And that solved the problem. I no longer need the customauth.urls file.
Just started with TastyPie to expose the data. Trying to tie together resources using tastypie.Api for urls.py.
But I get this error when I try to access them through localhost:api/**resource.
my api.py:
from tastypie.resources import ModelResource
from idg.models.molecule_dictionary import MoleculeDictionary
class MoleculeDictionaryResource(ModelResource):
class Meta:
queryset = MoleculeDictionary.objects.all()
# resource_name = 'moleculedictionary'
my url.py:
from django.conf.urls import url, include, patterns
from idg.api import MoleculeDictionaryResource
from django.contrib import admin
from tastypie.api import Api
from . import views
dictionary_resource = MoleculeDictionaryResource()
# private_api = Api(api_name='private')
# private_api.register(MoleculeDictionaryResource(), canonical=True)
urlpatterns = [
url(r'^$', views.index, name='index'),
# url(r'^exports/', include('data_exports.urls', namespace='data_exports')),
url(r'^api/', include(dictionary_resource.urls)),
]
Error:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/api/moleculedictionary/?format=json
Using the URLconf defined in django_root.urls, Django tried these URL patterns, in this order:
^__debug__/
xadmin/
^idg/
^comments/
^admin/
The current URL, api/moleculedictionary/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Any suggestions ? I am not sure where I made a mistake. I have followed the tutorial (https://django-tastypie.readthedocs.org/en/latest/tutorial.html)
Uncomment line
resource_name = 'moleculedictionary'
in Your api.py file.
Try this:
private_api = Api(api_name='v1')
private_api.register(MoleculeDictionaryResource(), canonical=True)
url(r'^api/', include(private_api.urls)),
Then you should be able to access it with /api/v1/