views.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import json
  2. from rest_framework import viewsets
  3. # Create your views here.
  4. from django.http import HttpResponse, JsonResponse
  5. from rest_framework.parsers import JSONParser
  6. from django.contrib.auth.models import User
  7. from rest_framework import serializers
  8. from rest_framework.response import Response
  9. from .models import UserProfile
  10. from .serializer import UserProfileSerializer, UserSerializer
  11. def user_list(request):
  12. '''
  13. List all users or create a user
  14. '''
  15. if request.method == 'GET':
  16. queryset = User.objects.all()
  17. serializer = UserSerializer(queryset, many=True)
  18. return JsonResponse(serializer.data, safe=False)
  19. elif request.method == 'POST':
  20. data = JSONParser().parse(request)
  21. serializer = UserSerializer(data=data)
  22. if serializer.is_valid():
  23. serializer.save()
  24. return JsonResponse(serializer.data, status=201)
  25. return JsonResponse(serializer.errors, status=400)
  26. def user_details(request, pk):
  27. if request.method == 'GET':
  28. try:
  29. queryset = User.objects.get(pk=pk)
  30. serializer = UserSerializer(queryset)
  31. return JsonResponse(serializer.data, safe=False)
  32. except:
  33. return JsonResponse({"error":"User does not exist"})
  34. def log_or_create(request, wallet):
  35. if request.method == 'POST':
  36. if UserProfile.objects.filter(wallet = wallet).exists():
  37. queryset = UserProfile.objects.get(wallet = wallet)
  38. queryset.visits += 1
  39. queryset.save()
  40. serializer = UserProfileSerializer(queryset)
  41. return JsonResponse(serializer.data, safe=False)
  42. else:
  43. UserProfile.objects.create(wallet = wallet, user="NOT_SET", visits = 1)
  44. queryset = UserProfile.objects.get(wallet = wallet)
  45. serializer = UserProfileSerializer(queryset)
  46. return JsonResponse(serializer.data, safe=False)
  47. # verific daca exista cont+ chia wallet
  48. # if exista return modelul userului
  49. # altfel create si return model user
  50. return JsonResponse({"error":"Work in progress"})
  51. def change_username(request, wallet, nickname):
  52. if request.method == 'POST':
  53. if UserProfile.objects.filter(wallet = wallet).exists():
  54. queryset = UserProfile.objects.get(wallet = wallet)
  55. queryset.user = nickname
  56. queryset.save()
  57. serializer = UserProfileSerializer(queryset)
  58. return JsonResponse(serializer.data, safe=False)