13

I'm trying to create an API view but I'm getting an error. Can anyone help?

urls.py:

app_name = 'ads'
urlpatterns = [
    # ex: /ads/
    url(r'^$', views.ListBrand.as_view(), name='brand_list'),
]

views.py:

from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from . import serializers


class ListBrand(APIView):
    def get(self, request, format=None):
        brands = models.Brand.objects.all()
        serializer = serializers.BrandSerializer(brands, many=True)
        data = serializer.data
        return Response(data)

UPDATE: HERE IS THE ERROR, it is a string error. And I can't seem to find where its coming from.

TypeError at /api/v1/ads/
'str' object is not callable
Request Method: GET
Request URL:    http://localhost/api/v1/ads/
Django Version: 1.10.2
Exception Type: TypeError
Exception Value:    
'str' object is not callable
Exception Location: C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py in <listcomp>, line 264
Python Executable:  C:\Users\Leon\Desktop\esriom\Scripts\python.exe
Python Version: 3.5.2
Python Path:    
['C:\\Users\\Leon\\Desktop\\esirom',
 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages\\setuptools-18.1-py3.5.egg',
 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages\\pip-7.1.0-py3.5.egg',
 'C:\\Users\\Leon\\Desktop\\esriom\\Scripts\\python35.zip',
 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs',
 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32\\lib',
 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32',
 'C:\\Users\\Leon\\Desktop\\esriom',
 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages']
Server time:    Fri, 7 Oct 2016 12:44:04 -0500

HERE IS THERE TRACEBACK TOO

Environment:


Request Method: GET
Request URL: http://localhost/api/v1/ads/

Django Version: 1.10.2
Python Version: 3.5.2
Installed Applications:
['rest_framework',
 'ads.apps.AdsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in dispatch
  457.         request = self.initialize_request(request, *args, **kwargs)

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in initialize_request
  364.             authenticators=self.get_authenticators(),

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in get_authenticators
  264.         return [auth() for auth in self.authentication_classes]

File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in <listcomp>
  264.         return [auth() for auth in self.authentication_classes]

Exception Type: TypeError at /api/v1/ads/
Exception Value: 'str' object is not callable
11
  • What error do you get? Commented Oct 7, 2016 at 18:14
  • You're making us guess where the error is happening. Please post the entire error traceback, including the line of code where the error actually occurs. Commented Oct 7, 2016 at 18:16
  • Do you have a __str__(self) function in your model? Like this: docs.djangoproject.com/en/1.10/ref/models/instances/#str Commented Oct 7, 2016 at 18:26
  • @1GDST yes i do def __str__(self): return self.name Commented Oct 7, 2016 at 18:28
  • What's the value of REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] in your settings.py? Commented Oct 7, 2016 at 18:40

4 Answers 4

22

My problem was in my settings.py file:

Diff:

    REST_FRAMEWORK = {
-       'DEFAULT_AUTHENTICATION_CLASSES': {
+       'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication',
-        }
+        ),
-        'DEFAULT_PERMISSION_CLASSES': {
+        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticatedOrReadOnly',
-        },
+        ),
    }
Sign up to request clarification or add additional context in comments.

4 Comments

Good to know you located the problem. The problem is because of this if condition: github.com/tomchristie/django-rest-framework/blob/3.4.7/…, which only considers list and tuple but not set.
the difference is the curly braces in case anyone spends a few minutes scrutinising the differences!
Ugh, derp. I wonder why tuples are preferred in Django settings; some tiny constant time/space savings over a list?
Oh, not since Dj 1.9 but it seems DRF didn't get the memo in its docs :P
10

Just want to give an example from the previous correct answers with Django v2.0.6 and Django REST framework v3.8.2.

For example in settings.py:

REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': {
            'rest_framework.authentication.BasicAuthentication',
            'rest_framework.authentication.SessionAuthentication',
            }
    }

Change:

'DEFAULT_AUTHENTICATION_CLASSES': {
                'rest_framework.authentication.BasicAuthentication',
                'rest_framework.authentication.SessionAuthentication',
                }

Into:

'DEFAULT_AUTHENTICATION_CLASSES': (
                'rest_framework.authentication.BasicAuthentication',
                'rest_framework.authentication.SessionAuthentication',
                )

By just replacing the "{ }" with "( )".

Comments

2

if you are using simple_jwt also check this , don't use these brackets {} but () and add comma at the end

    SIMPLE_JWT = {
   'AUTH_HEADER_TYPES': ('JWT',),
   'ACCESS_TOKEN_LIFETIME': timedelta(minutes=100),
#    'ROTATE_REFRESH_TOKENS': False,
#    'BLACKLIST_AFTER_ROTATION': False,
#    'UPDATE_LAST_LOGIN': False,
     'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
}

Comments

0

just replace {} by () in settings.py REST_FRAMEWORK

1 Comment

Could you clarify on why this would fix the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.