我正在使用djangorestframework django == 2.0使用Python 3.7
我放了一个这样的事件
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
from rest_framework.authtoken.models import Token
Token.objects.create(user=instance)
当我尝试创建用户时,编译器给出错误:
Exception Value:
type object 'Token' has no attribute 'objects'
尝试执行以下
>>> from rest_framework.authtoken.models import Token
>>> Token.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: type object 'Token' has no attribute 'objects'
如果发生上述错误,那是因为您没有在设置的安装_app中添加auth令牌。如果不是installed_apps中的,它是抽象的,并且没有默认管理器(对象)。
看来未创建Token
模型。因此,请确保您遵循文档中的安装。
确保您在INSTALLED_APPS
中有'rest_framework.authtoken'
另外, settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
另外,请确保您执行python manage.py makemigrations
,然后确保python manage.py migrate
创建Token
模型
首先检查您是否已在settings.py中的installed_apps下添加了 'rest_framework.authtoken'
。然后运行" python manage.py迁移"。
其次,您应该在为用户创建令牌的情况下打开新的python shell,而无需如下:
>>> `from django.contrib.auth.models import User`
>>> `from rest_framework.authtoken.models import Token`
>>> `user = User.objects.get(pk=1)`
>>> `Token.objects.create(user=user)`
&lt; token:efa5fc4a8b142cd20478a78abaaf9d763be44d6acc&gt;