[英]DRF can't authorize account via token, always getting anonymous user object
我正在使用TokenAuthentication並為用戶提供了模型Profile:
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"
但是,仍然無法理解為什么我無法讓用戶通過我的請求登錄。 我在哪里做錯了?
我太傻了。 匿名用戶是因為我沒有設置
authentication_classes = (TokenAuthentication,)
這就是為什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.