我正在使用 django 用户类和 rest_framework 令牌类来存储用户信息和令牌。同样,我正在使用serializers.ModelSerializer
类。但是当我发出更新请求(检查更新方法)来更新用户信息以及我拥有的令牌时,它给了我错误。
这是serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.authtoken.views import Token
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password']
extra_kwargs = {
'password' : {
'write_only':True,
'required': True
}
}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
Token.objects.create(user=user) # create token for the user
return user
def update(self, instance, validated_data):
instance.username = validated_data['username']
instance.set_password(validated_data['password'])
instance.save()
Token.objects.update(user=instance)
return instance
视图.py
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated, IsOwnerOfObject]
authentication_classes = (TokenAuthentication,)
网址.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('users', UserViewSet, basename = 'users')
urlpatterns = [
path('api/', include(router.urls)),
]
错误 :
django.db.utils.IntegrityError:唯一约束失败:authtoken_token.user_id
这就是我在标头字段中使用授权令牌发出请求的方式: