JasonGenX
JasonGenX

Reputation: 5434

Django Rest Framework: Can't get over strange error

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.

Upvotes: 0

Views: 250

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599600

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.

Upvotes: 2

Related Questions