example-of-crud-in-django-w.../app/library/views.py

55 lines
1.9 KiB
Python
Raw Normal View History

2021-07-14 16:19:03 +02:00
# app/Library/views.py
2021-07-12 07:01:26 +02:00
2021-07-05 15:56:53 +02:00
from django.http import JsonResponse
2021-07-12 23:47:31 +02:00
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
2021-07-14 16:19:03 +02:00
from .serializers import BookSerializer
from .models import Book
2021-07-05 15:56:53 +02:00
def ping(request):
data = {"ping": "pong!"}
return JsonResponse(data)
2021-07-12 07:01:26 +02:00
2021-07-14 16:19:03 +02:00
class BookList(APIView):
2021-07-13 18:18:18 +02:00
def get(self, request):
2021-07-14 16:19:03 +02:00
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
2021-07-12 23:47:31 +02:00
return Response(serializer.data, status=status.HTTP_200_OK)
2021-07-12 07:01:26 +02:00
def post(self, request):
2021-07-14 16:19:03 +02:00
serializer = BookSerializer(data=request.data)
2021-07-12 07:01:26 +02:00
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
2021-07-12 23:47:31 +02:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2021-07-14 16:19:03 +02:00
class BookDetails(APIView):
2021-07-13 18:18:18 +02:00
def get(self, request, pk):
2021-07-14 16:19:03 +02:00
book = Book.objects.filter(pk=pk).first()
if book:
serializer = BookSerializer(book)
2021-07-12 23:47:31 +02:00
return Response(serializer.data, status=status.HTTP_200_OK)
2021-07-13 18:18:18 +02:00
return Response(status=status.HTTP_404_NOT_FOUND)
2021-07-12 23:47:31 +02:00
2021-07-13 18:18:18 +02:00
def put(self, request, pk):
2021-07-14 16:19:03 +02:00
book = Book.objects.filter(pk=pk).first()
serializer = BookSerializer(book, data=request.data)
2021-07-13 19:37:12 +02:00
if serializer.is_valid():
2021-07-13 18:18:18 +02:00
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
2021-07-14 16:19:03 +02:00
elif not book:
2021-07-13 19:37:12 +02:00
return Response(serializer.data, status=status.HTTP_404_NOT_FOUND)
2021-07-13 18:18:18 +02:00
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
2021-07-14 16:19:03 +02:00
book = Book.objects.filter(pk=pk).first()
if book:
serializer = BookSerializer(book)
book.delete()
2021-07-13 18:18:18 +02:00
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(status=status.HTTP_404_NOT_FOUND)