Django RestFramework _'NoneType'对象没有属性'token'

时间:2018-05-26 17:24:47

标签: django django-rest-framework

我的User模型有这个Serializer类: serializers.py

class UserCreateSerializer(serializers.ModelSerializer):
    """User django serilization"""
    key = serializers.StringRelatedField(source='key.token', read_only=True)

    class Meta:
        model = User
        fields = ['phonenumber','id','email', 'username', 'key' ]

    def create(self, validate_data):
        user = User(**validate_data)
        user.save()
        return user

和这个views.py

class UserListView(ListAPIView):
    '''listing all users'''
    permission_classes = (AllowAny,)
    pagination_class = SmallPagination
    throttle_classes = (UserRateThrottle, AnonRateThrottle,)
    serializer_class = UserCreateSerializer
    queryset = User.objects.all()
    filter_backends = (filters.SearchFilter,)
    search_fields = ('username', 'phonenumber', 'email')

我在settings.py中加入了'rest_framework.authtoken', 并从django Restframe工作文档中为Tokens发出信号。

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

urls.py

urlpatterns = [
    re_path(r'^users/$', views.UserListView.as_view(), name='user-list'),]

所以当我尝试加载我的用户列表时会发生以下错误:

  

'NoneType'对象没有属性'token'

 for attr in attrs:
        try:
            if isinstance(instance, collections.Mapping):
                instance = instance[attr]
            else:
                instance = getattr(instance, attr) ...
        except ObjectDoesNotExist:
            return None
        if is_simple_callable(instance):
            try:
                instance = instance()
            except (AttributeError, KeyError) as exc:
....

错误位置来自:

  

/backend/env/lib/python3.6/site-packages/rest_framework/fields.py in   get_attribute

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/api/users/create/

Django Version: 2.0
Python Version: 3.6.3
Installed Applications:
['django.contrib.admin',
 'main.apps.MainConfig',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'stdimage',
 'rest_framework.authtoken',
 'blog',
 'taggit',
 'taggit_serializer',
 'django.contrib.sites',
 'corsheaders',
 'webpack_loader']
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 "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/django/views/generic/base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  494.             response = self.handle_exception(exc)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in handle_exception
  454.             self.raise_uncaught_exception(exc)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/views.py" in dispatch
  491.             response = handler(request, *args, **kwargs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/generics.py" in post
  192.         return self.create(request, *args, **kwargs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/mixins.py" in create
  22.         headers = self.get_success_headers(serializer.data)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  537.         ret = super(Serializer, self).data

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in data
  262.                 self._data = self.to_representation(self.instance)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
  491.                 attribute = field.get_attribute(instance)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/relations.py" in get_attribute
  177.         return get_attribute(instance, self.source_attrs)

File "/home/babyjesus/workspace/gamespawn/backend/env/lib/python3.6/site-packages/rest_framework/fields.py" in get_attribute
  100.                 instance = getattr(instance, attr)

Exception Type: AttributeError at /api/users/create/
Exception Value: 'NoneType' object has no attribute 'token'

2 个答案:

答案 0 :(得分:0)

authtoken模型对用户模型related_name=auth_token。因此,如果您需要从用户获取令牌,则应使用auth_token.key

key = serializers.StringRelatedField(source='auth_token.token', read_only=True)

答案 1 :(得分:0)

我也陷入了这个错误。但幸运的是我发现了我正在做的错误。 我知道它已经有一段时间了。仍然为陷入这种愚蠢错误的新手回答这个问题。 如果我们必须使用令牌模型,我们必须在 settings.py 文件中的 Installed Apps 中提及相同的内容

'rest_framework.authtoken'

之后进行迁移,您将在数据库中看到新表的创建。 之后你可以像这样查询数据库...

Token.objects.all()

你现在可以走了。

快乐编码。