我正在使用TokenAuthentication并为用户提供模型配置文件:
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"
});
注册工作正常,Token被创建,但是当我尝试发送此请求以创建配置文件,链接到已登录用户时,我每次都会获得匿名用户对象。 在我的设置中,我正在设置:
DEFAULT_AUTHENTICATION_CLASSES = "rest_framework.authentication.TokenAuthentication"
但是,仍然无法理解为什么我无法让用户登录我的请求。我在哪里做错了?
答案 0 :(得分:0)
我是白痴。匿名用户是因为我没有设置
authentication_classes = (TokenAuthentication,)
这就是原因。