AssertionError: Class UserSerializer missing "Meta" attribute while performing User Accounts Management on Django

AssertionError: Class UserSerializer missing "Meta" attribute while performing User Accounts Management on Django

我的 views.py 文件:

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UserSerializer


class TestView(APIView):
    def get(self, request, format=None):
        print("API called")
        return Response("You did it!", status=200)


class UserView(APIView):
    def post(self, request, format=None):
        print("User created")

        user_data = request.data
        print(request.data)
        user_serializer = UserSerializer(data=user_data)
        if user_serializer.is_valid(raise_exception=False):
            user_serializer.save()
            return Response({'user': user_data}, status=200)

        return Response({'msg': "error: no user created"}, status=400)

我的serializers.py文件:

from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.validators import UniqueValidator
from rest_framework.settings import api_settings


class UserSerializer(serializers.ModelSerializer):

    token = serializers.SerializerMethodField()

    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all())]
    )

    username = serializers.CharField(
        required=True,
        max_length=32,
        validators=[UniqueValidator(queryset=User.objects.all())]
    )

    first_name = serializers.CharField(
        required=True,
        max_length=32
    )

    last_name = serializers.CharField(
        required=True,
        max_length=32
    )

    password = serializers.CharField(
        required=True,
        min_length=8,
        write_only=True
    )

    def create(self, validated_data):
        password = validated_data.pop(password, None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def get_token(self, obj):
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(obj)
        token = jwt_encode_handler(payload)
        return token


class Meta:
    model = User
    fields = (
        'token'
        'username',
        'password',
        'first_name',
        'last_name',
        'email',
        'id'
    )

我的 urls.py 文件:

from django.urls import path
from .views import TestView, UserView
from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token

urlpatterns = [
    path('test', TestView.as_view()),
    path('user-view/', UserView.as_view()),
]

邮递员请求:

如您所见,我在这里发送用户名。我知道它会出错,因为我没有发送包含所有字段的完整数据,但是我得到的错误是完全不同的

然后这是我的命令:

您可以看到服务器运行没有错误,但即使 class Meta 存在,我仍然收到断言错误。请帮我解决错误!

P.S。我不知道这是否重要,但前端处于 react-native 状态,目前尚未集成。

我认为您错过了 UserSerializer 定义中的缩进。

class UserSerializer(serializers.ModelSerializer):

    ...    
    
    # here you need to indent so Meta belongs to the serializer.
    class Meta:
        model = User
        fields = (
            'token'
            'username',
            'password',
            'first_name',
            'last_name',
            'email',
            'id'
        )