def contact_list(request): if request.method == 'GET': contacts = Contact.objects.all() serializer = ContactSerializer(contacts) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ContactSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) else: return JSONResponse(serializer.errors, status=400)
def contact_detail(request, pk): try: contact = Contact.objects.get(pk=pk) except Contact.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ContactSerializer(contact) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = ContactSerializer(contact, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) else: return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': contact.delete() return HttpResponse(status=204)