1

I have a very basic Django Rest API.

I don't know how to have some HTML views, in the same django project, which uses API (finally keeping API returning JSON only).

I followed this, but it seems to change the API View (in this case, curl will retrieve HTML and not JSON) : https://www.django-rest-framework.org/api-guide/renderers/#templatehtmlrenderer

Do I need another Django App ? Another Django project ? Some JS ?

EDIT :

Ok, I've seen it's possible, thanks to rrebase.

But I can't retrieve the JSON with Curl, here my views.py

from rest_framework import generics
from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser

from . import models
from . import serializers

class UserListView(generics.ListAPIView):
    renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
    template_name = 'profile_list.html'

    def get(self, request):
        queryset = models.CustomUser.objects.all()
        serializer_class = serializers.UserSerializer
        return Response({'profiles': queryset})

My models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):

    def __str__(self):
        return self.email

I get an error "Object of type 'CustomUser' is not JSON serializable" when I request the API (http://127.0.0.1:8000/api/v1/users/)

Sorry, it's some different that initial question...

2 Answers 2

0

Yes, you can have both. The link you provided to docs has the following:

You can use TemplateHTMLRenderer either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.

When making an API request, set the ACCEPT request-header accordingly to html or json.

Sign up to request clarification or add additional context in comments.

Comments

0

Finally I made some conditions in my view, and it's working

class UserListView(generics.ListAPIView):
    renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
    permission_classes = (IsAdminUser,)

    def get(self, request):
        queryset = CustomUser.objects.all()

        if request.accepted_renderer.format == 'html':
            data = {'profiles': queryset}
            return Response(data, template_name='profile_list.html')
        else:
            serializer = UserSerializer(queryset, many=True)
            data = serializer.data
            return Response(data)

Comments

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.