def post(self, request, format=None): serializer = StudentSerializer(data=request.data) print('serializer', serializer) if serializer.is_valid(): serializer.save() return Response({'msg': 'Data Inserted'}, status=status.HTTP_201_CREATED) return Response(serializer.errors)
def put(self, request, pk, format=None): get_id = pk student = Student.objects.get(id=get_id) serializer = StudentSerializer(student, data=request.data) if serializer.is_valid(): serializer.save() return Response({'msg': 'Complete Data Updated.'}, status=status.HTTP_201_CREATED) return Response(serializer.errors)
def patch(self, request, pk, format=None): get_id = pk student = Student.objects.get(id=get_id) serializer = StudentSerializer(student, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response({'msg': 'Partial Data Updated'}) return Response(serializer.errors)
def student(request): if request.method == 'GET': json_data = request.body stream = io.BytesIO(json_data) python_data = JSONParser().parse(stream) id = python_data.get('id', None) if id is not None: stu = Student.objects.get(id=id) serializr = StudentSerializer(stu) json_data = JSONRenderer().render(serializr.data) return HttpResponse(json_data, content_type='application/json') else: stu = Student.objects.all() serializr = StudentSerializer(stu, many=True) json_data = JSONRenderer().render(serializr.data) return HttpResponse(json_data, content_type='application/json') if request.method == 'POST': json_data = request.body stream = io.BytesIO(json_data) python_data = JSONParser().parse(stream) serializr = StudentSerializer(data=python_data) if serializr.is_valid(): serializr.save() response = {'msg': 'Data inserted.'} json_data = JSONRenderer().render(response) return HttpResponse(json_data, content_type='application/json') else: json_data = JSONRenderer().render(serializr.errors) return HttpResponse(json_data, content_type='application/json') if request.method == 'PUT': json_data = request.body stream = io.BytesIO(json_data) python_data = JSONParser().parse(stream) id = python_data.get('id') stu = Student.objects.get(id=id) serializr = StudentSerializer(stu, data=python_data, partial=True) if serializr.is_valid(): serializr.save() response = {'msg': 'Data updated.'} json_data = JSONRenderer().render(response) return HttpResponse(json_data, content_type='application/json') # else: json_data = JSONRenderer().render(serializr.errors) return HttpResponse(json_data, content_type='application/json') if request.method == 'DELETE': json_data = request.body stream = io.BytesIO(json_data) python_data = JSONParser().parse(stream) id = python_data.get('id') stu = Student.objects.get(id=id) stu.delete() response = {'msg': 'Data deleted.'} # json_data = JSONRenderer().render(response) # return HttpResponse(json_data, content_type='application/json') return JsonResponse(response, safe=False)