0
我使用TokenAuthentication和對用戶模型簡介:爲配置文件創建DRF無法通過令牌授權帳戶,總是讓匿名用戶對象
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
participant = models.CharField(max_length=255)
title = models.CharField(max_length=100)
,並查看:
class ProfileView(LoggingMixin, GenericAPIView):
serializer_class = ProfileSerializer
queryset = Profile.objects.all()
def get(self, request, format=None):
"""
Return user's profile information
"""
serializer = ProfileSerializer(queryset)
return Response(serializer.data)
def post(self, request, format=None):
"""
Create new profile
"""
data = request.data.copy()
data['user'] = request.user.id
print data
serializer = self.serializer_class(data=data, context={"request":request})
print serializer
if serializer.is_valid():
print 1
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
我需要註冊後創建配置文件對象。我從一個網頁通過jQuery發送數據:
$.ajax({
headers: {"Authorization": "Token " + data.key},
type: "POST",
url: "http://127.0.0.1:8002/v1/profiles/",
data: JSON.stringify(profileDataToSend),
success: function(){
console.log('Success! 2');
},
dataType: "json",
contentType : "application/json"
});
登記工作正常,令牌被創建,但是當我嘗試發送該請求創建一個配置文件,鏈接到登錄的用戶,我收到匿名用戶對象的每時間。 在我的設置我設置:
DEFAULT_AUTHENTICATION_CLASSES = "rest_framework.authentication.TokenAuthentication"
但儘管如此,不明白爲什麼我不能讓用戶登錄符合我的要求。我在哪裏做錯了?