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: []
url. TheHyperlinkedModelSerializerby default will create the url for you. check the api response json you should see a url for each user.