1

I'm using using Django Rest Framework's HyperlinkedModelSerializer, ModelViewset, and DefaultRouter, and end up with good URLs like this: http://localhost:8000/api/users/1. I would like to, given a user id, find the fully-qualified url for that user without hard-coding anything. Given 53, I want http://localhost:8000/api/users/1, and the host should change when I move to production.

# from urls.py
router = routers.DefaultRouter()
router.register(r'users', shared_views.UserViewSet)


# from models.py
class UserViewSet(viewsets.ModelViewSet):
    '''
    endpoint for viewing/editing users
    '''
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


# from serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')

How can I do this? I tried: reverse(UserViewSet.as_view({'get': 'retrieve'}), args=[request.user.id]) but got this error:

Reverse for 'shared.views.UserViewSet' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

1
  • 1
    you don't need to create the url . The HyperlinkedModelSerializer by default will create the url for you. check the api response json you should see a url for each user. Commented Nov 26, 2015 at 7:02

1 Answer 1

1

As @Anush said, I can use the serializer to get the URL. The request needs to be passed in a particular way as a keyword argument (see below):

class OwnedViewSet(viewsets.ModelViewSet):
    ''' ModelViewSets that use hyperlinked model serializers
        can inherit this to automatically
        set `owner` = current user. 
    '''
    def create(self, request, *args, **kwargs):
        serialized_owner = UserSerializer(request.user, context={'request': request})
        request.data['owner'] = serialized_owner.data['url']
        return super(OwnedViewSet, self).create(request, *args, **kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

Looking back on this, I am even more struck by how Django Rest Framework does the best it can with bad abstractions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.