You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Django REST Framework获取用户资料时遇ProfileSerializer参数错误

问题解决:TypeError: ProfileSerializer() takes no arguments

核心问题

你的ProfileSerializer类没有继承Django REST Framework的序列化基类,导致实例化时无法接收传入的profile对象,引发参数错误。

修正步骤

1. 修复序列化器代码

修改serializer.py,让ProfileSerializer继承serializers.ModelSerializer:

from rest_framework import serializers
from .models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['image','full_name','bio','phone','dob','gender','country','state','city','address','longitude','latitude','zipcode','facebook','instagram','twitter','whatsApp']

2. 优化视图(可选,更符合"获取登录用户资料"需求)

既然需求是获取登录用户自己的个人资料,不需要在URL中传递pk,直接通过request.user关联的Profile获取即可,这样更安全合理:

修改MyProfileView:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from .models import Profile
from .serializers import ProfileSerializer

class MyProfileView(APIView):
    permission_classes = [permissions.IsAuthenticated]
    
    def get(self, request, format=None):
        # 假设Profile和User是一对一关联,关联字段为user
        profile = Profile.objects.get(user=request.user)
        serializer = ProfileSerializer(profile)
        return Response(serializer.data)

修改urls.py:

path("my-profile/", MyProfileView.as_view(), name="my-profile"),

这样用户访问/api/my-profile/即可获取自己的资料,无需手动输入pk,也避免了用户访问他人资料的问题。

内容的提问来源于stack exchange,提问作者Destiny Franks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:40:47