Home » Django & REST Api » How to implement Edit and Delete with Django REST Framework ?

How to implement Edit and Delete with Django REST Framework ?

As we have seen in our previous post, “Writing class based Views in Django REST Framework” we written class based views for user’s information. As we add new entries into our database, it’s obvious we will need to edit some data from any of those entries sometimes or need to delete the entries altogether if we don’t want that data.

This post, helps you with how you can edit and delete the JSON objects from django rest framework REST API’s.

Edit existing user

Edit is supported with http PUT method, the implement of the “put” in views will be as below,

    def put(self, request, user_id, format=None):
        user = UserInfo.objects.get(userid=user_id)
        serializer = UserInfoSerializer(user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Delete Existing User / Multiple users

The “delete” implementation of views will be as below,

    def delete(self, request, user_name, format=None):
        user = UserInfo.objects.filter(username=user_name)
        if user:
            user.delete()
            return JsonResponse({"status":"ok"}, status=status.HTTP_200_OK)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

For more details about DELETE, you may refer to “How to delete single and multiple objects in Django / DRF”


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment