序列化程序和json响应出现奇怪的错误

时间:2019-11-19 19:45:38

标签: python django django-rest-framework

我有一个配置文件模型,可以使用“ 全部”序列化和设置字段。问题是,当我运行它时,出现以下错误:

AttributeError at /api/accounts/profile/
'User' object has no attribute 'following'

我尝试手动设置字段并得到相同的错误,但是当我从字段中删除以下内容时,它可以正常运行,并且得到正常的JSON响应,但是所有字段都显示为null,而不是我在管理面板中设置的数据

{
    "pk": 2,
    "date_of_birth": null,
    "bio": null,
    "profile_photo": null,
    "sex": null,
    "type_of_body": null,
    "feet": null,
    "inches": null,
    "lives_in": null
}

下面是应用程序其余部分的代码

models.py

class Profile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
    date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB")
    bio = models.TextField(max_length=500, null=True, blank=True)
    profile_photo = models.CharField(blank=True, null=True, max_length=300)
    sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True)
    type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True)
    feet = models.PositiveIntegerField(blank=True, null=True)
    inches = models.PositiveIntegerField(blank=True, null=True)
    lives_in = models.CharField(max_length=50, blank=True, null=True)
    updated_on = models.DateTimeField(auto_now_add=True)

serializers.py

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = '__all__'
        read_only_fields = ('pk', 'user', 'following', 'height')

views.py

class CurrentUserProfileAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        serializer = ProfileSerializer(request.user)
        return Response(serializer.data)

urls.py

urlpatterns = [
    url(r'^profile/$', CurrentUserProfileAPIView.as_view(), name="my_profile")
]

1 个答案:

答案 0 :(得分:0)

public class TARTrackerControllerTests { public static ILogger<TARTrackerController> Logger = Mock.Of<ILogger<TARTrackerController>>(); public static Mock<ITARRepository> Repository = new Mock<ITARRepository>(); public class GetTARTrackersTests { [Fact] public async Task Returns_OK_With_ListItemDTO() { //arrange var id = 12345; IEnumerable<ListItemDTO> expected = new List<ListItemDTO>(); Repository .Setup(repo => repo.GetListAsync<ListItemDTO>(It.IsAny<string>(), It.IsAny<object>())) .ReturnsAsync(expected); var controller = new TARTrackerController(Logger, Repository.Object); //act var result = await controller.Get(id); //assert var objResult = Assert.IsType<OkObjectResult>(result); Assert.Equal(typeof(IEnumerable<ListItemDTO>), objResult.Value.GetType()); } } } 返回request.user的实例(或任何未经身份验证的用户的settings.AUTH_USER_MODEL)–请求的 user ,但您正在尝试序列化使用AnonymousUser模型(Profile)的序列化程序。

由于用户没有提到的ProfileSerializer模型的属性,因此所有字段都将使用Profile进行序列化。 nullpk,它存在于任何Django模型实例中(始终指代使用的公钥)。

相关问题