字段名称user_username对于模型配置文件无效

时间:2017-09-30 04:28:14

标签: python django django-forms django-rest-framework

错误名称:字段名称user_username对模型Profile

无效

我正在构建我的编辑个人资料视图。

这是我的views.py

class ProfileEditAPIView(DestroyModelMixin, UpdateModelMixin, generics.RetrieveAPIView):
    serializer_class = ProfileEditSerializer

    def get_queryset(self):
        logged_in_user = User.objects.filter(username=self.request.user.username)
        return logged_in_user

    def get_object(self):
        queryset = self.get_queryset()
        obj = get_object_or_404(queryset)
        return obj.profile

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

我可以正确获取user_id,但无论如何我无法访问其用户名字段

这是serializers.py

class ProfileEditSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'user_username', <<<
            'title',
            'gender',
            'birth',
            'height',
            'height_in_ft',
            'profile_img',
        )

models.py

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    title = models.TextField(max_length=155, blank=True)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, default='u') # Recommend Factor
    location = models.CharField(max_length=40, choices=LOCATION_CHOICES, default='ud') # Recommend Factor
    birth = models.DateField(default='1992-07-23', blank=True, null=True) # Recommend Factor
    height = models.CharField(max_length=5, default='undefined')
    height_in_ft = models.BooleanField(default=True)
    profile_img = models.ImageField(
        upload_to=upload_location,
        null=True,
        blank=True)

为什么我们无法访问用户的用户名?我们如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:1)

您可以使用此方式从username模型中获取User

class ProfileEditSerializer(serializers.ModelSerializer):
    username = serializers.CharField(read_only=True, source="user.username")

    class Meta:
        model = Profile
        fields = (
            'username',
            'title',
            . . . .
        )

答案 1 :(得分:0)

尝试调用用户名,就像在模型中查看用户名一样。

更改:

        fields = (
        'user_username', <<<
        'title',
        'gender',
        'birth',
        'height',
        'height_in_ft',
        'profile_img',
    )

收件人:

        fields = (
        'user', 
        'title',
        'gender',
        'birth',
        'height',
        'height_in_ft',
        'profile_img',
    )

但是,如果您希望它在json响应中显示为用户名,请使用:

class ProfileEditSerializer(serializers.ModelSerializer):
   username = serializers.CharField(source='user')


class Meta:
    model = Profile
    fields = (
        'username', <<<
        'title',
        'gender',
        'birth',
        'height',
        'height_in_ft',
        'profile_img',
    )