HyperlinkedIdentityField在串行器上下文中需要该请求。添加上下文= {'request':request}

时间:2019-11-20 06:58:56

标签: python django django-rest-framework django-views django-serializer

我收到一条错误消息: HyperlinkedIdentityField在串行器上下文中需要该请求。实例化序列化程序时添加context={'request': request}。当我使用API​​获取数据时。我在这里做什么错了?

models.py

class User(AbstractUser):
    username = models.CharField(blank=True, null=True, max_length=255)
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    def __str__(self):
        return "{}".format(self.email)


class UserProfile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile')
    title = models.CharField(max_length=5)
    dob = models.DateField()
    address = models.CharField(max_length=255)
    country = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    zip = models.CharField(max_length=5)
    photo = models.ImageField(upload_to='uploads', blank=True, )

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo')


class UserSerializer(serializers.HyperlinkedModelSerializer):
    profile = UserProfileSerializer(required=True)
    class Meta:
        model = User
        fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        password = validated_data.pop('password')
        user = User(**validated_data)
        user.set_password(password)
        user.save()
        UserProfile.objects.create(user=user, **profile_data)
        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile')
        profile = instance.profile

        instance.email = validated_data.get('email', instance.email)
        instance.save()

        profile.title = profile_data.get('title', profile.title)
        profile.dob = profile_data.get('dob', profile.dob)
        profile.address = profile_data.get('address', profile.address)
        profile.country = profile_data.get('country', profile.country)
        profile.city = profile_data.get('city', profile.city)
        profile.zip = profile_data.get('zip', profile.zip)
        profile.photo = profile_data.get('photo', profile.photo)
        profile.save()
        return instance

and views.py

class UserList(ListCreateAPIView):
    '''
    Return list all users or create a new user
    '''
    serializer_class = UserSerializer
    pagination_class = CustomPagination

    def get_queryset(self):
        try:
            user = User.objects.all()
            return user
        except:
            content = {
                'status': 'Not Found'
            }
            return Response(content, status=status.HTTP_404_NOT_FOUND)

    def get(self, request):
        users = self.get_queryset()
        paginate_queryset = self.paginate_queryset(users)
        serializer = self.serializer_class(paginate_queryset, many=True)
        return self.get_paginated_response(serializer.data, )

    def post(self, request):
        try:
            serializer = UserSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except:
            content = {
                'status': 'Failed to create new user'
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

class UserDetail(RetrieveUpdateDestroyAPIView):
    def get_queryset(self, pk):
        try:
            user = User.objects.get(pk=pk)
            return user
        except User.DoesNotExist:
            content = {
                'status': 'Not Found'
            }
            return Response(content, status=status.HTTP_404_NOT_FOUND)

    def get(self, request, pk):
        try:
            user = self.get_queryset(pk)
            serializer = UserSerializer(user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        except NameError:
            content = {
                'status': 'Failed to get user'
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, pk):
        try:
            user = self.get_queryset(pk)
            serializer = UserSerializer(user, request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_200_OK)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except:
            content = {
                'status': 'Failed to modify user'
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        try:
            user = self.get_queryset(pk)
            user.delete()
            return Response("Delete user: " +user.username +"successfully",
                            status=status.HTTP_200_OK)
        except:
            content = {
                'status': 'Failed to delete user'
            }
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

我正在尝试使用

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

并且有效。我不知道为什么会有区别。如果我在代码中添加context = {'request':request}。我将收到一个新错误。真不舒服

0 个答案:

没有答案