...

/

Writing Post Viewsets

Writing Post Viewsets

Learn to create viewset for the Post model, and create a sample post to test the endpoint.

For the following endpoint, we’ll only be allowing the POST and GET methods. This will help us have the basic features working first.

Requirements

The code should follow these rules:

  • Only authenticated users can create posts.

  • Only authenticated users can read posts.

  • Only GET and POST methods are allowed.

Inside the post directory, create a file called viewsets.py. Into the file, add the following content:

Press + to interact
from rest_framework.permissions import IsAuthenticated
from core.abstract.viewsets import AbstractViewSet
from core.post.models import Post
from core.post.serializers import PostSerializer
class PostViewSet(AbstractViewSet):
http_method_names = ('post', 'get')
permission_classes = (IsAuthenticated,)
serializer_class = PostSerializer
def get_queryset(self):
return Post.objects.all()
def get_object(self):
obj = Post.objects.get_object_by_public_id(self.kwargs['pk'])
self.check_object_permissions(self.request, obj)
return obj
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response(serializer.data, status=status.HTTP_201_CREATED)

In the preceding code, we defined three interesting methods:

  • The get_queryset method returns all the posts. We don’t actually have particular ...