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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| from .models import * from .serializers import *
from django.shortcuts import render from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from django.views.decorators.csrf import csrf_exempt
from bson import ObjectId
from django.http import HttpResponse, JsonResponse
@csrf_exempt @api_view(['POST']) def add_post(request): data = JSONParser().parse(request) comment = data['comment'].split(",") tags = data['tags'].split(",") user_details = {"first_name" : data['user_details']['first_name'], "last_name" : data['user_details']['last_name'],} post = Posts( post_title= data['post_title'], post_description= data['post_description'], comment =comment, tags = tags, user_details = user_details ) post.save()
try: serializer = PostSerializer(post) return JsonResponse(serializer.data , status=201) except: return JsonResponse(serializer.errors, status=400)
@csrf_exempt @api_view(['POST']) def update_post(request,id):
data = JSONParser().parse(request) try: post = Posts.objects.get(id=id)
post.comment = data['comment'].split(",") post.tags = data['tags'].split(",") post.user_details = {"first_name" : data['user_details']['first_name'], "last_name" : data['user_details']['last_name']} post.post_title= data['post_title'] post.post_description= data['post_description'] post.save()
result = {"received": True, "detail" : "updated_" + str(id)} return JsonResponse(result, status=201)
except: result= {"error" : {"code": 404, "detail" : "Post Not Found"}} return JsonResponse(result, status=400)
@csrf_exempt @api_view(['GET']) def delete_post(request,id): try: post = Posts.objects.get(id=id) post.delete()
result = {"received": True, "detail" : "deleted_" + str(id) } return JsonResponse(result, status=201) except: result= {"error" : {"code": 404, "detail" : "Post Not Found"}} return JsonResponse(result, status=201)
@csrf_exempt @api_view(['GET']) def read_post(requests,id): try: post = Posts.objects.get(id=id) except: result= {"error" : {"code": 404, "detail" : "Post Not Found"}} return JsonResponse(result, status=201) try: serializer = PostSerializer(post) return JsonResponse(serializer.data , status=201) except: return JsonResponse(serializer.errors, status=400)
@csrf_exempt @api_view(['POST']) def read_posts(request): posts = Posts.objects.all() if len(posts) == 0: result= {"error" : {"code": 404, "detail" : "Post Not Found"}} return JsonResponse(result, status=400) else: result = {"answer" : []} for post in posts: serializer = PostSerializer(post) result['answer'].append(serializer.data)
return JsonResponse(result , status=201)
|