views.py
2.8 KB
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
from rest_framework import viewsets, permissions, generics, mixins, status
from rest_framework.response import Response
from knox.models import AuthToken
from .models import UserGroup
from user.models import User
from .serializers import (UserGroupSerializer, CreateUserGroupSerializer, AddUserSerializer)
from user.serializers import UserSerializer
class CreateGroupAPI(generics.GenericAPIView):
serializer_class = CreateUserGroupSerializer
permission_classes = [permissions.IsAuthenticated]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
input_name = request.data["group_name"]
input_owner = UserSerializer(self.request.user).data
group, created = UserGroup.objects.get_or_create(group_name = input_name, owner_email = input_owner["email"])
if created:
group.save()
group.user_to_group(request.user)
group.save()
else:
body = {"message": "already exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
return Response(UserGroupSerializer(group).data)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class AddUserAPI(generics.GenericAPIView):
serializer_class = AddUserSerializer
permission_classes = [permissions.IsAuthenticated]
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
input_name = request.data["group_name"]
input_user = request.data["user_id"]
input_owner = UserSerializer(self.request.user).data
group, created = UserGroup.objects.get_or_create(group_name = input_name)
if(input_owner["email"]!=UserGroupSerializer(group).data["owner_email"]):
body = {"message": "not group owner"}
return Response(body, status=status.HTTP_401_UNAUTHORIZED)
if created:
body = {"message": "group doesn't exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
else:
try :
user= User.objects.get(id = input_user)
except User.DoesNotExist:
body = {"message": "user doesn't exist"}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
group.user_to_group(user)
group.save()
return Response(UserGroupSerializer(group).data)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
class GroupListAPI(generics.ListAPIView):
queryset = UserGroup.objects.all()
serializer_class = UserGroupSerializer
#class GroupListAPI(generics.GenericAPIView):