0

Now I have tried to use nested routers to solve the issue but still Iwant to be able to create new comments without sending the blog post ID from the request body. I want to be able to get it from request parameters. So, how can I get this id one and use it to create new comment

http://127.0.0.1:8000/blog-posts/1/comments/

My routes looks like this.


from rest_framework_extensions.routers import NestedRouterMixin

class NestedDefaultRouter(NestedRouterMixin, DefaultRouter):
    pass

router = NestedDefaultRouter()

blog_posts_router = router.register('blog-posts', BlogPostViewSet)

blog_posts_router.register(
    'comments',
    CommentViewSet,
    base_name='comments',
    parents_query_lookups=['blog_post']

)

urlpatterns = [
    path('', include(router.urls))
]

and this is how my Views are looking like

from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import BlogPost, Comment
from .serializers import BlogPostSerializer, CommentSerializer
from rest_framework.decorators import action
from django.http import JsonResponse
import json
from rest_framework_extensions.mixins import NestedViewSetMixin


class BlogPostViewSet(NestedViewSetMixin, ModelViewSet):
    """ Handles creating, updating, listing and deleting blog posts. """

    serializer_class = BlogPostSerializer
    queryset = BlogPost.objects.all()


class CommentViewSet(NestedViewSetMixin, ModelViewSet):
    """ Handles creating, updating, listing and deleting comments on blog posts. """

    serializer_class = CommentSerializer
    queryset = Comment.objects.all()

Thank you I'm waiting for your help. I couldn't find it from the documentations

Mwibutsa Floribert
  • 1,824
  • 14
  • 21

1 Answers1

0

What you can do to achieve that is to inherit the create function of the viewset and use the kwarg parameter to access the id of the post. Then add the post id to the request data before passing it to a serializer and using it to create a new object.

 def create(self, request, *args, **kwargs):
    post_id = kwargs['parent_lookup_post']
    new_data = request.data.copy()
    new_data['post'] = post_id
    serializer = self.get_serializer(data=new_data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
reedonne
  • 76
  • 3
  • Actually I have managed to solve this using Nested routers but the other issue is that I'm not able to grab that id and use it to create new comments instead of submitting it every time in my post request – Mwibutsa Floribert Jul 24 '19 at 16:29