TIL: Making a Django REST framework view do server-side rendering

#til #django #djangorestramework #python

On a recent project I found myself needing one classic form-and-template style page in an otherwise API-driven project. I could, of course, just do it with a regular view function, but I had a bunch of authentication and suchlike set up for DRF APIViews.

Turns out it's actually pretty easy to make an APIView kick it oldschool!

from rest_framework.parsers import FormParser
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView


class OldSchoolView(APIView):
    parser_classes = [FormParser]
    renderer_classes = [TemplateHTMLRenderer]
    template_name = "path/to/a/template.html"

    def get(self, request):
        context = {}
        # do regular view stuff here
        return Response(context)

    def post(self, request):
        formdata = request.data.dict()
        # do regular view stuff here
        return Response()  # or redirect; whatever's appropriate

The indicated template gets rendered with the context you pass to the Response.

I think you could write a view that simultaneously supports HTML and JSON with content negotiation, but it ended up being more trouble that it was worth in my case.