axios django rest框架无法识别定义为外键的用户

yiytaume  于 2023-06-22  发布在  iOS
关注(0)|答案(2)|浏览(128)

我试图在django模型中保存用户配置文件信息。模型定义如下

class UserProfile(models.Model): 
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  reg_date = models.DateTimeField(auto_now_add=True, blank=True)
  name = models.CharField(max_length=30, blank=True)
  family = models.CharField(max_length=30,  blank=True)
  phoneNumber = models.CharField(max_length=20,  blank=True)

  def __str__(self) :
    return self.name + self.family

模型的序列化器定义为:

class UserProfileSerializer(serializers.ModelSerializer): 
  class Meta: 
    model= UserProfile
    fields = ['user', 'reg_date', 'name', 'family', 'phoneNumber']

视图如下:

class UserProfileView(viewsets.ViewSet): 
  def create(self, request): 
    UserProfile.objects.create(user = request.user)

我使用axios发送一个post请求,如下所示:

const a = await ProfileAPI.post('',
        {
          headers: {
            'Authorization': mytoken
          }
        })

其中 mytoken 是dj-rest-auth API提供的登录用户令牌。虽然token是OK的,并且请求执行了UserProfileView,但我在django rest中得到了以下错误:

ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001F069C59190>": "UserProfile.user" must be a "User" instance.

我错过了什么吗?我的请求或视图有问题吗?请帮我解决这个问题

xjreopfe

xjreopfe1#

添加到settings.py AUTH_USER_MODEL = '(app name).UserProfile'

k0pti3hp

k0pti3hp2#

认证的确定方法

身份验证方案始终被定义为类列表。REST框架将尝试对列表中的每个类进行身份验证,并将使用成功身份验证的第一个类的返回值设置request.userrequest.auth
如果没有类进行身份验证,request.user将被设置为django.contrib.auth.models.AnonymousUser的示例,request.auth将被设置为None
未验证请求的request.user和request.auth值可以使用UAUTHENICATED_USER和UAUTHENICATED_TOKEN设置修改。

设置

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

浏览次数

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'auth': str(request.auth),  # None
        }
        return Response(content)

如何发送token请求

// get the token from where you've stored, localStorage is just an example
const token = localStorage.getItem("myToken")
const response = await axios.post('my-api/', {
  headers: {
    'Authorization': `Token ${myToken}`
  }
})

相关问题