|
| 1 | +from django.shortcuts import get_object_or_404 |
| 2 | +from rest_framework.views import APIView |
| 3 | +from rest_framework.response import Response |
| 4 | +from rest_framework import status |
| 5 | +from .models import Prompt |
| 6 | +from .serializers import PromptSerializer |
| 7 | +# from .serializers import PromptReadSerializer |
| 8 | + |
| 9 | + |
| 10 | +# from django.http import JsonResponse |
| 11 | + |
| 12 | +class Prompts(APIView): |
| 13 | + permission_classes=() |
| 14 | + serializer_class=PromptSerializer |
| 15 | + |
| 16 | + def get(self, request): |
| 17 | + """Index Request""" |
| 18 | + prompts = Prompt.objects.all() |
| 19 | + data = PromptSerializer(prompts, many=True).data |
| 20 | + return Response({"prompt": data}) |
| 21 | + # prompts = Prompt.objects.filter(owner=request.user.id) |
| 22 | + |
| 23 | + def post(self, request): |
| 24 | + """Create a Prompt""" |
| 25 | + serializer = PromptSerializer(data=request.data) |
| 26 | + if serializer.is_valid(): |
| 27 | + serializer.save() |
| 28 | + return Response(serializer.data, status=status.HTTP_201_CREATED) |
| 29 | + else: |
| 30 | + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
| 31 | + |
| 32 | + |
| 33 | +class PromptDetail(APIView): |
| 34 | + permission_classes=() |
| 35 | + def get(self, request, pk): |
| 36 | + """Show one Prompt""" |
| 37 | + prompt = get_object_or_404(Prompt, pk=pk) |
| 38 | + |
| 39 | + # if not request.user.id == mango.owner.id: |
| 40 | + # raise PermissionDenied('Unauthorized, you do not own this mango') |
| 41 | + |
| 42 | + # Run the data through the serializer so it's formatted |
| 43 | + data = PromptSerializer(prompt).data |
| 44 | + return Response({ 'prompt': data }) |
| 45 | + |
| 46 | + def patch(self, request, pk): |
| 47 | + """Update a Prompt""" |
| 48 | + prompt = get_object_or_404(Prompt, pk=pk) |
| 49 | + ms = PromptSerializer(prompt, data=request.data, partial=True) |
| 50 | + if ms.is_valid(): |
| 51 | + ms.save() |
| 52 | + return Response(ms.data) |
| 53 | + return Response(ms.errors, status=status.HTTP_400_BAD_REQUEST) |
| 54 | + |
| 55 | + def delete(self, request, pk): |
| 56 | + """Delete Request""" |
| 57 | + prompt = get_object_or_404(Prompt, pk=pk) |
| 58 | + prompt.delete() |
| 59 | + return Response(status=status.HTTP_204_NO_CONTENT) |
0 commit comments