Skip to content

Improper Docs in Tutorial 5 causing error when using HyperlinkedModelSerializer #9729

@alihassancods

Description

@alihassancods

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:

  1. Follow the tutorial instructions exactly as written.

  2. Start the server.

  3. Make a GET request to retrieve a snippet detail (or browse in the browsable API).

  4. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions