예제 #1
0
파일: views.py 프로젝트: fremeva/DRFClass
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)
예제 #2
0
파일: views.py 프로젝트: danimaky/DRFClass
 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)
예제 #3
0
파일: views.py 프로젝트: fremeva/DRFClass
 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)
예제 #4
0
파일: views.py 프로젝트: fremeva/DRFClass
 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)