Django Rest Framework: Can't get over strange error - django

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.

Related

Django is unable to find the view used for query params the other views are working perfectly

#urls.py
from django.urls import include,path
from rest_framework import routers
from . import views
router=routers.DefaultRouter()
router.register(r'banks',views.BanksViewSet)
router.register(r'branches',views.BranchesViewSet)
router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches')
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
#views.py
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import BanksSerializer,BranchesSerializer
from .models import Banks,Branches
class BanksViewSet(viewsets.ModelViewSet):
queryset=Banks.objects.all().order_by('id')
serializer_class= BanksSerializer
class BranchesViewSet(viewsets.ModelViewSet):
queryset=Branches.objects.all().order_by('ifsc')
serializer_class=BranchesSerializer
class BranchAutocompleteViewSet(viewsets.ModelViewSet):
serializer_class=BranchesSerializer
def get_queryset(self):
branchName=self.request.query_params.get("q")
limit=self.request.query_params.get("limit")
offset=self.request.query_params.get("offset")
queryset=Branches.objects.filter(branch__startswith=branchName).order_by('ifsc')[offset:limit]
return queryset
the BanksViewSet and BranchesViewSet are working fine but the other one is not working
the problem might be the basename in urls.py as changing it doesn't do anything even when left as an empty string.
this is what the console has:
Django version 3.1.5, using settings 'bankApi.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /branches/autocomplete/
[19/Jan/2021 18:30:04] "GET /branches/autocomplete/?q=A&limit=5&offset=0 HTTP/1.1" 404 12148
Make sure your root url branches registered last like this:
...
router.register(r'banks',views.BanksViewSet)
router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches')
router.register(r'branches',views.BranchesViewSet) # root of 'branches' is last
...

DRF: AttributeError: type object 'Plan' has no attribute 'get_extra_actions' [duplicate]

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.

Im getting an error regarding TemplateView in CBV django

Class-based TemplateView are not working, help me find the error
from django.shortcuts import render
from django.views.generic.base import View,TemplateView
from django.http import HttpResponse
# Create your views here.
class home(TemplateView):
template_name = 'index.html'
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['injectme'] = 'injected'
return context
url.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from basicapp import views
urlpatterns = [
url(r'^$',views.home.as_view(),name = 'home'),
path('admin/', admin.site.urls),
]
TypeError at /
expected str, bytes or os.PathLike object, not tuple
Request Method: GET
Request URL: http://127.0.0.1:8000/ Django Version: 2.2 Exception
Type: TypeError Exception Value: expected str, bytes or os.PathLike
object, not tuple Exception
Location: /anaconda3/envs/mydjangoEnv/lib/python3.7/posixpath.py in
join, line 80 Python
Executable: /anaconda3/envs/mydjangoEnv/bin/python Python
Version: 3.7.3 Python Path:
['/Users/faiq/Desktop/exercise/CBV/advance',
'/anaconda3/envs/mydjangoEnv/lib/python37.zip',
'/anaconda3/envs/mydjangoEnv/lib/python3.7',
'/anaconda3/envs/mydjangoEnv/lib/python3.7/lib-dynload',
'/anaconda3/envs/mydjangoEnv/lib/python3.7/site-packages'] Server
time: Wed, 8 May 2019 23:02:58 +0000

A Schema is required to be provided to GraphQLView

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

django piston Circular reference detected while emitting response when using model

Am facing a problem with configuring piston for django, every time I specify the model name it runs I get the below error
RuntimeError at /en/vehicle/api/car.json
Circular reference detected while emitting response
Request Method: GET
Request URL: http://127.0.0.1:8000/en/vehicle/api/car.json
Django Version: 1.4.1
Exception Type: RuntimeError
Exception Value:
Circular reference detected while emitting response
Exception Location: /Users/mo/Projects/pythonic/gar-env/lib/python2.7/site-packages/piston/emitters.py in _any, line 109
Python Executable: /Users/mo/Projects/pythonic/gar-env/bin/python
Below is my handelrs.py
from piston.handler import BaseHandler
from piston.utils import rc, throttle, translate_mime
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.db.models.loading import get_model
from models import (ModelLookUpI18n as ModelLookup, Image)
from forms import CarForm, ModelLookUpForm, ModelLookUpI18nForm
from django.http import HttpResponse
import logging, json, os
from piston.utils import validate
from django.conf import settings
from django.utils.translation import ugettext as _
class CarHandler(BaseHandler):
"""
CarHandler
"""
allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
model = Car
fields = ('id', 'model', 'description', 'primary_image', 'color', 'mileage', 'view_count', 'asking_price')
def read(self, request):
params = dict()
params.update({'status' : self.model.STATUS_ACTIVE})
return self.model.objects.filter(**params).order_by('created_at')
in the url.py here is my code
from django.conf.urls import *
from handlers import CarHandler
from piston.resource import Resource
car_resource = Resource(CarHandler)
# API URL schema
urlpatterns += patterns('',
# car API
url(r'^api/car\.(?P<emitter_format>.+)', car_resource, name='vehicle-api-car'),
)
The error is coming at run time, I cannot find a solution to the problem. I tried to remove model and fields attribute from CarHandler class that would make it work. I tired to use get_model and load at run time but again, I would get the same runtime error.
Please advise?
Is 'model' a foreign key reference? Is it possible Piston is including 'model' in the output, which itself may have a reference back to the Car model it was included in?