John Baek John Baek - 3 years ago 269
Python Question

Field name user_username is not valid for model Profile

Error Name: Field name

is not valid for model

I'm building my Edit Profile View.

Here is my

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)

I can get user_id correctly but somehow I can't access to its username field

This is

class ProfileEditSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = (
'user_username', <<<

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(

Why can't we access to user's username? And how can we solve this?


Answer Source

You can get the username from User model using this way.

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

    class Meta:
        model = Profile
        fields = (
            . . . .
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download