-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Description
The official Tutorial 5 Relationships & Hyperlinked APIs doesn't mentions that when using HyperlinkedModelSerializer in manually instantiated serializers inside views (e.g., SnippetDetail, SnippetList), you must pass context={'request': request}.
Without this, url and related fields fail to resolve and raise errors like:
HyperlinkedIdentityField
requires the request in the serializer context. Add context={'request': request}
when instantiating the serializer.
Here is my view:
class SnippetDetailsOOP(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_object(self,pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404
def get(self,request,pk,format=None):
data = self.get_object(pk)
serializer = SnSerializer(data)
return Response(serializer.data)
def put(self,request,pk,format=None):
snippetdata = self.get_object(pk)
serializer = SnSerializer(snippetdata,data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Steps to reproduce:
-
Follow the tutorial instructions exactly as written.
-
Start the server.
-
Make a GET request to retrieve a snippet detail (or browse in the browsable API).
-
Observe the error due to missing context.
Importance :
Official Documentation is misguiding the people wasting their precious time and while being discussed on various forums, this hasn't been resolved till yet. I have solved this issue in my version of repo, i can open a PR after discussion.