def post(self, request): group_id = request.data.get("group_id") if group_id is None: return Response({"success": False, "message": "Required Param group_id is missing"}, status=400) try: existing_group = Group.objects.get(pk=group_id) except Group.DoesNotExist: return Response({"success": False, "message": "Invalid group_id param is provided"}, status=400) if int(existing_group.created_by.id) != int(request.user.id): return Response({"success": False, "message": "User can not edit group"}, status=400) try: group_icon = request.FILES['group_icon'] except MultiValueDictKeyError: group_icon = None data = {"group_name": request.data.get("group_name"), "created_by": request.user.id, "group_description": request.data.get("group_description"), "group_icon": group_icon} group = GroupSerializer(data=data) if group.is_valid(): if group_icon is not None: existing_group.group_icon = data.get("group_icon") existing_group.group_name = data.get("group_name") existing_group.group_description = data.get("group_description") existing_group.save() serializer = GroupSerializer(existing_group, many=False) return Response({"success": True, "message": "Group Updated", "data": serializer.data}) return Response({"success": False, "message": group.errors}, status=400)
def create_group(self, request): serializer = GroupSerializer(data=request.data, partial=True) if not serializer.is_valid(): return response406({ **serializer.errors, 'message': 'Złe dane wejściowe' }) serializer.save(owner=request.user) return response200(data=serializer.data)
def post(self, request): try: group_icon = request.FILES['group_icon'] except MultiValueDictKeyError: group_icon = None data = {"group_name": request.data.get("group_name"), "created_by": request.user.id, "group_description": request.data.get("group_description"), "group_icon": group_icon} group = GroupSerializer(data=data) if group.is_valid(): instance = group.save() serializer = GroupSerializer(instance, many=False, context={'request': request}) return Response({"success": True, "message": "Group Created", "data": serializer.data}) return Response({"success": False, "message": group.errors})
class AcademicChargeGetGroupsSerializer(serializers.ModelSerializer): groupDictate = GroupSerializer(read_only=True) class Meta: model = AcademicCharge fields = ['groupDictate', 'teacherDictate']
class PostSerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField('get_owner') group = GroupSerializer(many=False, read_only=True) def to_representation(self, instance): to_return = super().to_representation(instance) to_return['group'] = { 'id': to_return['group']['id'], 'name': to_return['group']['name'] } if to_return['image']: to_return['image'] = 'http://' + self.context['host'] + to_return[ 'image'] if to_return['file']: to_return[ 'file'] = 'http://' + self.context['host'] + to_return['file'] return to_return def get_owner(self, instance): return UserSerializer(instance=instance.owner, context=self.context).data class Meta: model = Post fields = [ 'id', 'owner', 'content', 'date_posted', 'group', 'file', 'image' ] read_only_fields = ['owner', 'group']
def test_specific_group_search(self): group = Group.objects.create(name="Searchable") response = self.get_response("groups/Searchable") content = loads(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(content.get("results")), 1) self.assertEqual(content.get("results"), [GroupSerializer(group).data])
def test_query_param_club_id(self): request = self.factory.get("/groups/", {"club": self.club.pk}) response = get_response(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data.get("results")), 2) self.assertEqual(response.data.get("results"), GroupSerializer(self.groups, many=True).data)
def groups_list(self, request): groups = Group.objects.none() groups = groups.union(Group.objects.filter(owner=request.user)).union( Group.objects.filter(members=request.user)) serializer = GroupSerializer(groups, many=True) paginator = PageNumberPagination() data = paginator.paginate_queryset(serializer.data, request) return paginator.get_paginated_response(data=data)
def post(self, request): group_owned_qs = Group.objects.filter(created_by=request.user.id).values_list('pk', flat=True) group_joined_qs = GroupMembers.objects.filter(member=request.user.id).values_list('group', flat=True) groups_by_users = list(group_owned_qs) + list(group_joined_qs) unique_ids = list(dict.fromkeys(groups_by_users)) groups = Group.objects.filter(pk__in=unique_ids).order_by('-created_at') serializer = GroupSerializer(groups, many=True, context={'request': request}) return Response({"success": True, "data": serializer.data})
def remove_student(self, request, pk=None): group = self.get_object() student_id = request.data.get('student') student = Student.objects.get(id=student_id) group.students.remove(student) remove_perm('groups.view_group', student.user, group) group.save() return Response(GroupSerializer(group).data)
class AccessRuleSerializer(serializers.ModelSerializer): post = PostSerializer(read_only=True) group = GroupSerializer(read_only=True) class Meta: model = AccessRule fields = ('post', 'group', 'visibility', 'order', 'receiver_response', 'notification_email', 'notify_when')
def test_query_param_sport_id(self): request = self.factory.get("/groups/", {"sport": self.sport.pk}) response = get_response(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data.get("results")), 1) self.assertEqual( response.data.get("results")[0], GroupSerializer(self.group).data)
class SubjectDetailSerializer(serializers.ModelSerializer): group = GroupSerializer() lecturer = TeacherBriefInfoSerializer() lab_teacher = TeacherBriefInfoSerializer() practic_teacher = TeacherBriefInfoSerializer() class Meta: model = Subject fields = '__all__'
def test_group_list(self): request = self.factory.get("/groups/") response = get_response(request) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data.keys(), {"count", "next", "previous", "results"}) self.assertEqual(len(response.data.get("results")), len(self.groups)) self.assertEqual(response.data.get("results"), GroupSerializer(self.groups, many=True).data)
def get(self, request): print('i am hear') groups = Group.objects.filter(manager=request.user).all() serializer = GroupSerializer(groups, many=True) return Response({ 'groups': serializer.data, 'form': { 'name': 'group_name' } })
def details(self, request, **kwargs): try: group = Group.objects.get(id=kwargs.get('id')) except Group.DoesNotExist: return response404('Group') self.check_object_permissions(request=request, obj=group) return response200({ **GroupSerializer(group).data, 'message': 'Pomyślnie dodano grupę' })
class FeedSerializer(serializers.ModelSerializer): content_object = GenericRelatedField({ Story: StorySerializer(), Character: CharacterSerializer(), Plot: PlotSerializer(), Group: GroupSerializer(), }) class Meta: model = Feed fields = ['id', 'content_object', 'created_at', 'feed_content']
class AcademicChargeGetbyTeacherSerializer(serializers.ModelSerializer): groupDictate = GroupSerializer(read_only=True) courseDictate = CourseSerializer(read_only=True) class Meta: model = AcademicCharge fields = [ 'codeAcademicCharge', 'groupDictate', 'courseDictate', 'teacherDictate' ]
class EnrollmentSerializer(serializers.ModelSerializer): groupEnrollment = GroupSerializer() journeyEnrollment = JourneySerializer() studentEnrollment = StudentSerializer() class Meta: model = Enrollment fields = [ 'codeEnrollment', 'groupEnrollment', 'journeyEnrollment', 'studentEnrollment', 'dateEnrollment', 'is_active' ]
def update_group(request, group_id): payload = json.loads(request.body) try: group_item = Group.objects.filter(id=group_id) group_item.update(**payload) group = Group.objects.get(id=group_id) serializer = GroupSerializer(group) return JsonResponse(serializer.data, safe=False, status=status.HTTP_200_OK) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def post(self, request): serializer = GroupSerializer(data=request.data) serializer.is_valid(raise_exception=True) group = serializer.save(manager=request.user) groups = Group.objects.filter(manager=request.user).all() serializer = GroupSerializer(groups, many=True) return Response({ 'msg': f' вы успешно создали группу {group.name}', 'groups': serializer.data, 'form': { 'name': 'group_name' } })
def update_group(self, request, **kwargs): try: group = Group.objects.get(**kwargs) except Group.DoesNotExist: return response404('Group') self.check_object_permissions(request=request, obj=group) serializer = GroupSerializer(group, data=request.data, partial=True) if 'moderator' in request.data.keys(): user = User.objects.get(id=request.data.get('moderator')) group.moderator = user request.data.pop('moderator') if 'image' in request.FILES.keys(): group.image = request.FILES.get('image') request.data.pop('image') group.save() if not serializer.is_valid(): return response406({ **serializer.errors, 'message': 'Błąd walidacji' }) serializer.save() return response200( data={ **serializer.data, 'message': 'Pomyślnie zaktualizowano grupę' })
def search_for_groups(self, request): try: search_phrase = request.GET['phrase'] except MultiValueDictKeyError: return response406({'message': 'Złe dane wejściowe'}) groups = Group.objects.filter(name__icontains=search_phrase) final_groups = [ group for group in groups if (request.user not in group.members.all()) and ( group.owner != request.user) ] groups_data = GroupSerializer(final_groups, many=True).data paginator = PageNumberPagination() data = paginator.paginate_queryset(groups_data, request) return paginator.get_paginated_response(data)
def create_group(request): try: payload = json.loads(request.body) group = Group.objects.create( name=payload["name"], color=payload["color"], admin=payload["admin"] ) serializer = GroupSerializer(group) return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def create_course_group(self, request, pk=None): course = self.get_object() group_name = request.data.get('name') group = Group(name=group_name, course=course) group.save() for student in group.students.all(): assign_perm('groups.view_group', student.user, group) # Assign view permission to students in group for assistant in group.course.assistant_set.all(): assign_perm('groups.view_group', assistant.user, group) assign_perm('groups.change_group', assistant.user, group) assign_perm('groups.change_group', group.course.professor.user, group) assign_perm('groups.delete_group', group.course.professor.user, group) assign_perm('groups.view_group', group.course.professor.user, group) return Response(GroupSerializer(group).data)
def GroupList(request): if request.method == 'GET': contacts = Group.objects.all() serializer = GroupSerializer(contacts, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = GroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, pk, format=None): user = self.get_object(pk) requser = request.user if user.is_private: if user not in requser.friends.all(): if Groups.objects.filter(admins=requser,members=user,is_private=False).exists(): groups = Groups.objects.filter(admins=requser,members=user,is_private=False).distinct() elif Groups.objects.filter(members__in=[user,requser],is_private=False).exists(): groups = Groups.objects.filter(members__in=[user,requser],is_private=False).distinct() else: groups = None else: q = (Q(created_by=user)|Q(members = user)|Q(admins = user)) groups = Groups.objects.filter(q,is_private=False).order_by('-id').distinct() else: if user not in requser.friends.all(): if Groups.objects.filter(members=requser,admins=user,is_private=False).exists(): groups = Groups.objects.filter(members=requser,admins=user,is_private=False).distinct() elif Groups.objects.filter(admins=requser,members=user,is_private=False).exists(): groups = Groups.objects.filter(admins=requser,members=user,is_private=False).distinct() else: groups = None else: q = (Q(created_by=user)|Q(members = user)|Q(admins = user)) groups = Groups.objects.filter(q,is_private=False).order_by('-id').distinct() kw = request.GET.get('kw') if kw: groups = groups.filter(name__icontains=kw) serializer = GroupSerializer(groups, many=True) serializedgroups = serializer.data if groups: if (groups.count() > 7): groups_list1 = serializedgroups[0:7] groups_lists = [serializedgroups[x:x+8] for x in range(7, (groups.count()),8)] groups_lists.insert(0,groups_list1) else: groups_lists = [serializedgroups[x:x+7] for x in range(0, (groups.count()),7)] else: groups_lists = [] return Response(groups_lists)
def get(self, request, format=None): q = (Q(created_by=self.request.user) | Q(members=self.request.user) | Q(admins=self.request.user)) groups = Groups.objects.filter(q).order_by('-id').distinct() groupserializer = GroupSerializer(groups, many=True) today = datetime.today() event_access = EventsAccess.objects.filter( user=request.user).values_list('event', flat=True) q = (Q(created_by=request.user) | Q(id__in=event_access)) events = Events.objects.filter( q, end_date__gte=today.date).order_by('start_date').distinct() eventserializer = EventListSerializer(events, many=True) data = { 'groups': groupserializer.data, 'events': eventserializer.data, } return Response(data)
class PostSerializer(serializers.ModelSerializer): author = AccountSerializer(read_only=True, required=False) shared_with = GroupSerializer(read_only=True, many=True, required=False) type = serializers.SerializerMethodField() def get_type(self, obj): return 'post' class Meta: model = Post fields = ('id', 'type', 'author', 'shared_with', 'content', 'created_at', 'updated_at', 'start_time', 'notification', 'notify_when', 'repeat', 'location_event', 'description_event', 'begin_time', 'end_time', 'end_repeat', 'show_date', 'show_begin_time', 'show_end_time', 'not_all_day', 'day_of_week', 'need_repeat', 'is_week_set', 'week_num', 'duration', 'pud', 'pud_time', 'is_holiday', 'is_updated') read_only_fields = ('id', 'created_at', 'updated_at') def get_validation_exclusions(self, *args, **kwargs): exclusions = super(PostSerializer, self).get_validation_exclusions() return exclusions + ['author']
def post(self, request): # show posts by group creater and members or show group posts page = request.data.get("page") if page is None: page = 1 size = 10 group_id = request.data.get("group_id") if group_id is None: return Response({"success": False, "message": "Required Param group_id is missing"}, status=400) try: existing_group = Group.objects.get(pk=group_id) except Group.DoesNotExist: return Response({"success": False, "message": "Invalid group_id param is provided"}, status=400) group_posts = GroupPost.objects.filter(group=existing_group.id).values_list("post", flat=True) posts = Post.objects.filter(pk__in=group_posts).order_by('-created_at') try: paginated_data = Paginator(posts, size) except (EmptyPage, InvalidPage): return Response({"success": False, "message": "Empty Page"}, status=400) feed_serializer = FeedSerializer(paginated_data.page(page), many=True, context={'request': request}) group_serializer = GroupSerializer(existing_group, many=False, context={'request': request}) return Response({"data": feed_serializer.data, "total": paginated_data.count, "pages": paginated_data.num_pages, "current_page": int(page), "group": group_serializer.data})