def get_snippets(request, pk=None): if request.method.upper() == 'GET': if pk is not None: snippet = get_object_or_404(Snippet, pk=pk) serializer = SnippetModelSerializer(snippet) else: snippets = Snippet.objects.all() serializer = SnippetModelSerializer(snippets, many=True) return JsonResponse(serializer.data) if request.method.upper() == 'POST': serializer = SnippetModelSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save() obj.user = User.objects.get(pk=1) obj.save() serializer = SnippetModelSerializer(obj) return JsonResponse(serializer.data, status=201) if request.method.upper() in ['PUT', 'PATCH']: serializer = SnippetModelSerializer(data=request.data) if serializer.is_valid(): obj = Snippet.objects.get(pk=pk) obj.title = request.data['title'] obj.code = request.data['code'] obj.lang = request.data['lang'] obj.save() serializer = SnippetModelSerializer(obj) return JsonResponse(serializer.data, status=201) if request.method.upper() == "DELETE": obj = get_object_or_404(Snippet.objects.filter(pk=pk)) obj.delete() return Response(status=204)
def partial_update(self, request, pk=None, *args, **kwargs): partial = kwargs.pop('partial', False) instance = Snippet.objects.get(pk=pk) serializer = SnippetModelSerializer(data=request.data) serializer.is_valid(raise_exception=True) for key, value in serializer.data.items(): setattr(instance, key, value) instance.save() return Response(serializer.data)
def post(self, request, *args, **kwargs): serializer = SnippetModelSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save() obj.user = User.objects.get(pk=1) obj.save() serializer = SnippetModelSerializer(obj) return JsonResponse(serializer.data, status=201)
def put(self, request, pk, *args, **kwargs): serializer = SnippetModelSerializer(data=request.data) if serializer.is_valid(): obj = Snippet.objects.get(pk=pk) obj.title = request.data['title'] obj.code = request.data['code'] obj.lang = request.data['lang'] obj.save() serializer = SnippetModelSerializer(obj) return JsonResponse(serializer.data, status=201)