【问题标题】:'str' object is not callable Django Rest Framework'str' 对象不可调用 Django Rest 框架
【发布时间】:2017-02-16 19:34:26
【问题描述】:

我正在尝试创建 API 视图,但出现错误。有人可以帮忙吗?

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)

更新:这是错误,这是一个字符串错误。而且我似乎找不到它的来源。

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

这里也有追溯

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

【问题讨论】:

  • 你得到什么错误?
  • 你让我们猜测错误发生在哪里。请发布整个错误回溯,包括实际发生错误的代码行。
  • 您的模型中有__str__(self) 函数吗?像这样:docs.djangoproject.com/en/1.10/ref/models/instances/#str
  • @1GDST 是的,我愿意def __str__(self): return self.name
  • REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] 在您的settings.py 中的值是多少?

标签: python django python-3.x django-rest-framework


【解决方案1】:

只需在 settings.py REST_FRAMEWORK 中将 {} 替换为 ()

【讨论】:

  • 您能否解释一下为什么这会解决问题?
【解决方案2】:

只是想从前面的正确答案中举一个例子,使用 Django v2.0.6 和 Django REST framework v3.8.2。

例如在settings.py中:

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

变化:

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

进入:

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

只需将“{ }”替换为“( )”即可。

【讨论】:

    【解决方案3】:

    我的问题出在我的 settings.py 文件中:

    差异:

        REST_FRAMEWORK = {
    -       'DEFAULT_AUTHENTICATION_CLASSES': {
    +       'DEFAULT_AUTHENTICATION_CLASSES': (
                'rest_framework.authentication.SessionAuthentication',
    -        }
    +        ),
    -        'DEFAULT_PERMISSION_CLASSES': {
    +        'DEFAULT_PERMISSION_CLASSES': (
                'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    -        },
    +        ),
        }
    

    【讨论】:

    • 很高兴知道您找到了问题所在。问题是因为这个if条件:github.com/tomchristie/django-rest-framework/blob/3.4.7/…,它只考虑list和tuple而不考虑set。
    • 不同之处在于花括号,以防有人花几分钟仔细检查差异!
    • 呃,笨蛋。我想知道为什么在 Django 设置中首选元组;在列表中节省一些微小的恒定时间/空间?
    • 哦,自从Dj 1.9 之后就没有了,但 DRF 似乎没有在其文档:P 中获得备忘录
    猜你喜欢
    • 2011-06-07
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2020-11-11
    • 2014-10-27
    • 2012-06-04
    • 2010-11-26
    相关资源
    最近更新 更多