from rest_framework import viewsets from rest_framework import permiss

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from posts.models import Post
from posts.serializers import PostSerializer
@api_view(['GET', ])
def api_detail_post_view(request, post_id):
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.methid == "GET":
serializer = PostSerializer(post)
return Response(serializer.data)
@api_view(['POST'])
def api_create_post_view(request):
if request.method == 'POST':
data = request.data
serializer = PostSerializer(data=data)
data = {}
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# @api_view(['POST', ])
# def api_create_post_view(request):
# post = Post()
# if request.method == "POST":
# serializer = PostSerializer(post, data=request.data)
# data = {}
# if serializer.is_valid():
# serializer.save()
# return Response(serializer.data, status=status.HTTP_201_CREATED)
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['PUT', ])
def api_update_post_view(request, post_id):
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.methid == "PUT":
serializer = PostSerializer(post, data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
data["success"] = "update successful"
return Response(data=data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['DELETE', ])
def api_delete_post_view(request, post_id):
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.methid == "DELETE":
operation = post.delete()
data = {}
if operation:
data["success"] = "delete successful"
else:
data["failure"] = "delete failed"
return Response(data=data)