Skip to content
Advertisement

Capturing values from url in post request in Django

I want to capture url values from a url into my views in a post request.

My urls.py looks like below

from django.urls import path from . import views as projects_views

urlpatterns = [
    path('<str:project_id>/comments', projects_views.ProjectCommentList.as_view(), name="project_comments"),
]

and I want to capture the value project_id in my ListCreateAPIView. Get call works fine.

My views.py looks like below

class ProjectCommentList(generics.ListCreateAPIView):
    queryset = projects_models.Comment.objects.all()
    serializer_class = projects_serializers.CommentSerializer


    def get(self, request, project_id=None):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = queryset.filter(project__id=project_id)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def perform_create(self, serializer):
        project_id = ###  Need "project_id" here
        project = projects_models.Project.objects.get(id=data.get('project_id'))
        serializer.save(project=project)

How can this be done?

Advertisement

Answer

Use self.kwargs["project_id"] to get the project_id in perform_create() method,

class ProjectCommentList(generics.ListCreateAPIView):
    ...

    def perform_create(self, serializer):
        project_id = self.kwargs["project_id"]
        project = projects_models.Project.objects.get(id=data.get('project_id'))
        serializer.save(project=project)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement