Django keyword error but print kwargs shows the key
I have this URL and I send the currently logged in user's id (viewer (33)) and the id of the user being looked at (user (1)) in the URL:
path("users/<int:viewer>/<int:user>/profile/", OtherProfile.as_view()),
Here is the view handling that URL:
class OtherProfile(generics.RetrieveAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = ProfileSerializer
name = "other-profile"
lookup_field = "user"
def get_queryset(self):
breakpoint()
viewer = self.kwargs["viewer"]
user = self.kwargs["user"]
return Profile.objects.all().filter(user_id=user)
There is a breakpoint here and the result of
print(self.kwargs["viewer"]) gives 33 which is correct
print(self.kwargs["user"]) gives 1 which is also correct
Here is the profile serializer as specified in the serializer_class:
class ProfileSerializer(serializers.ModelSerializer):
location = serializers.SerializerMethodField()
user = UserSerializer()
followers = serializers.SerializerMethodField()
class Meta:
model = Profile
fields = [
"id",
"background",
"photo",
"first_name",
"middle_name",
"last_name",
"birthdate",
"gender",
"bio",
"occupation",
"is_verified",
"verification",
"website",
"location",
"user",
"followers",
"created_at",
"updated_at",
]
def get_location(self, obj):
location_obj = Location.objects.filter(profile=obj.id)
if location_obj:
location_obj = Location.objects.get(profile=obj.id)
location = LocationSerializer(location_obj)
return location.data
def get_followers(self, obj):
breakpoint()
followers = Follow.objects.filter(followee=obj.user.id)
return followers.count()
I put a breakpoint on the get_followers method so I can look at the data.
print(self.context["view"].kwargs) - prints ["viewer", "user"]
My question:
Why does print(self.context["view"].kwargs["user"]) print 33 when on the view the kwargs user should be 1?
Why does it give me a key error when I try and print(self.context["view"].kwargs["viewer"])?