我想知道为什么我的Django项目中没有生成令牌。在我看来,一切正常,但现在我得到了:
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
django_1 | response = get_response(request)
django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
django_1 | response = self.process_exception_by_middleware(e, request)
django_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
django_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
django_1 | File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
django_1 | return view_func(*args, **kwargs)
django_1 | File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
django_1 | return self.dispatch(request, *args, **kwargs)
django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 489, in dispatch
django_1 | response = self.handle_exception(exc)
django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 449, in handle_exception
django_1 | self.raise_uncaught_exception(exc)
django_1 | File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 486, in dispatch
django_1 | response = handler(request, *args, **kwargs)
django_1 | File "/code/myProject/backend/myProject/companies/views.py", line 43, in post
django_1 | return Response({'token': user.auth_token.key, 'id': user.id}, status=status.HTTP_200_OK)
django_1 | File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 404, in __get__
django_1 | self.related.get_accessor_name()
django_1 | django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: User has no auth_token.
我检查了我的数据库并且没有令牌。显然我可以通过管理面板添加它然后它可以工作,但当然它应该在用户登录时自动生成。任何想法为什么它不起作用?
url(r'^login', views.UserAuthenticationView.as_view()),
views.py:
@permission_classes([CustomPermission])
class UserAuthenticationView(GenericAPIView):
serializer_class = UserAuthenticationSerializer
def post(self, request, *args, **kwargs):
serializer = UserAuthenticationSerializer(data=self.request.data)
if serializer.is_valid():
user = serializer.validated_data['user']
return Response({'token': user.auth_token.key, 'id': user.id}, status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)
serializers.py:
class UserAuthenticationSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user:
if not user.is_active:
msg = 'User account is disabled.'
raise serializers.ValidationError(msg, code='authorization')
else:
msg = 'Unable to log in with provided credentials.'
raise serializers.ValidationError(msg, code='authorization')
else:
msg = 'Must include "username" and "password".'
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
答案 0 :(得分:0)
您应手动get
或create
Token
。
get_or_create
方法非常适合:
from rest_framework.authtoken.models import Token
@permission_classes([CustomPermission])
class UserAuthenticationView(GenericAPIView):
serializer_class = UserAuthenticationSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
response_data = {
'id': user.id,
'token': token.key
}
return Response(response_data, status=status.HTTP_200_OK)
现在Token
如果尚未存在,将会生成,或者如果已经创建,将从数据库中获取。{/ p>
注意:您可以将raise_exception=True
参数传递给is_valid()
,以便不要编写此if
语句。