svalemento
svalemento

Reputation: 722

How to return html or json from ViewSets depending on client django rest framework

I've created an APIs endpoints for mobile developers with all of the logic there. Now I need to create a web version of this app. Is it possible to not write the views specifically for this, but use already existing one in APIs? In API I am using Django Rest Framework ViewSets. Assume that this is my models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=20)
    description = models.CharField(max_length=100, blank=True, null=True)

Then this is going to be my serializers.py:

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('id', 'title', 'description')
        read_only_fields = ('id',)

viewsets.py:

from rest_framework import viewsets
from .serializers import PostSerializer
from .models import Post

class PostViewSet(viewsets.ModelViewSet):
    model = Post
    queryset = Post.objects.all()
    serializer_class = PostSerializer

urls.py

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'posts', viewsets.Post, base_name='post')
urlpatterns = router.urls

I've seen this HTML & Forms in docs, but if I put renderer_classes and template_name it just renders html with the parameters that I want, but I want to have a separate endpoints for just returning json for mobile developers and rendering a user-friendly html for web version. Is it possible to do this and if it is, how do I handle this?

Upvotes: 3

Views: 4646

Answers (1)

Samuel Omole
Samuel Omole

Reputation: 185

I think you will have to manually create a separate endpoint to handle HTML requests, but you can easily achieve this using Template Renderers

Upvotes: 2

Related Questions