views.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import json
  2. from django.shortcuts import render
  3. from django.shortcuts import get_object_or_404
  4. from rest_framework import viewsets
  5. # Create your views here.
  6. from django.http import HttpResponse, JsonResponse
  7. from rest_framework.parsers import JSONParser
  8. from django.contrib.auth.models import User
  9. from rest_framework import serializers
  10. from rest_framework.response import Response
  11. from .serializer import UserProfileSerializer, UserSerializer
  12. def user_list(request):
  13. '''
  14. List all users or create a user
  15. '''
  16. if request.method == 'GET':
  17. queryset = User.objects.all()
  18. serializer = UserSerializer(queryset, many=True)
  19. return JsonResponse(serializer.data, safe=False)
  20. elif request.method == 'POST':
  21. data = JSONParser().parse(request)
  22. serializer = UserSerializer(data=data)
  23. if serializer.is_valid():
  24. serializer.save()
  25. return JsonResponse(serializer.data, status=201)
  26. return JsonResponse(serializer.errors, status=400)
  27. def user_details(request, pk):
  28. if request.method == 'GET':
  29. try:
  30. queryset = User.objects.get(pk=pk)
  31. serializer = UserSerializer(queryset)
  32. return JsonResponse(serializer.data, safe=False)
  33. except:
  34. return JsonResponse({"error":"User does not exist"})