0
votes

In my Django code, I have a Profile class which basically extends AbstractUser. I wanted the detail view for this user to use the username instead of the userid, and that is actually working perfectly.

In my urls.py, I have url(r'^profile/view/(?P<username>[\w.@+-]+)/$', ProfileDetail.as_view(), name="profile-detail") and my ProfileDetail class looks like this:

class ProfileDetail(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()
    lookup_field = 'username'

accompanied by this line in my Profile serializer: url = serializers.HyperlinkedIdentityField(view_name='profile-detail', lookup_field='username').

This all works great. The problem is when I attempt to view all of my user's "Swipes". My Swipe class has a foreign key relationship with my Profile class (and related_name='swipes' in this foreign key).

I added this to urls.py: url(r'^profile/view/(?P<username>[\w.@+-]+)/swipes/$', ProfileSwipesList.as_view(), name="swipe-detail") where my ProfileSwipesList class looks like:

class ProfileSwipesList(generics.ListAPIView):
    serializer_class = SwipeSerializer

    def get_queryset(self, *args, **kwargs):
        return Swipe.objects.filter(user = Profile.objects.get(username=self.kwargs['username']))

I verified that the queryset is returning the correct thing, a queryset of Swipe objects. In my Swipe serializer, I tried adding a similar line as the one I added in my Profile serializer: url = serializers.HyperlinkedIdentityField(view_name='swipe-detail').

However, when I try accessing this URL, I get this error:

Could not resolve URL for hyperlinked relationship using view name "swipe-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

I'm new to Django, so forgive me if the solution to this is obvious, but I'd appreciate any help with how to get this view to correctly show the queryset I'm returning from my list view.

1

1 Answers

0
votes

Try setting lookup_field on ProfileSwipesList and add the lookup_field to the respective HyperlinkedIdentityField.

Edit:

Based on your comment, you need to use a custom hyperlinked identify field.

class SwipeIdentityField(serializers.HyperlinkedIdentityField):
    def get_url(self, obj, view_name, request, format):
        # Unsaved objects will not yet have a valid URL.
        if hasattr(obj, 'pk') and obj.pk in (None, ''):
            return None
        url_kwargs = {
            'username': obj.user.username,
        }
        return reverse(
            view_name, kwargs=url_kwargs, request=request, format=format)


class SwipeSerializer:
    url = serializers.HyperlinkedIdentityField(view_name='swipe-detail')