I create API in django withdjango-rest-framework
.我有一个名为Comment
的模型,每个Comment
都有一个UserId
。我正在通过rest-auth.
每个User
都有一个我在前端使用的令牌来创建用户。
from django.db import models
import uuid
from django.utils.timezone import now
from django.contrib.auth.models import User
class Comment(models.Model):
CommentId= models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False)
DataCreated = models.DateField(default=now, editable=False)
UserId = models.ForeignKey(User, on_delete=models.CASCADE,
default=uuid.uuid4, editable=False)
Name = models.CharField(max_length=120, default="")
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('CommentId', 'DataCreated', 'UserId', 'Name')
我创建了一个保存新评论的 simpre 视图
@api_view(['POST'])
def addComment(request):
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
关键是,在request.data
我收到的数据是Name
和Token
而不是UserId
,所以我想知道如何从Token
获得UserId
?
我不记得昵称的用户在这里写了正确的答案,但我不太明白,因为我还不知道如何使用 api。
所以我复制答案
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def addComment(request):
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
serializer.save(UserId=request.user)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
在settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
发送请求时,您需要添加标头Authorization: Token ${token}
(我不知道这就是我收到错误的原因(