def get_friend(self, obj): user = self.context['request'].user if obj.giver == user: return UserListSerializer(obj.taker).data else: return UserListSerializer(obj.giver).data
def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = UserListSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = UserListSerializer(queryset, many=True) return Response(serializer.data)
def post(self, request, *args, **kwargs): form = UserListForm(request.data) if not form.is_valid(): return Response({'Detail': form.errors}, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data user_list = self.get_user_list() serializer = UserListSerializer(user_list) list_data = serializer.list_data(**cld) if isinstance(list_data, Exception): return Response({'Detail': list_data.args}, status=status.HTTP_400_BAD_REQUEST) return Response(list_data, status=status.HTTP_200_OK)
def list(self, request, *args, **kwargs): queryset = self.filter_queryset(User.objects.order_by('id')) page = self.paginate_queryset(queryset) if page is not None: serializer = UserListSerializer(page, many=True, context={'request': request}) return self.get_paginated_response(serializer.data) serializer = UserListSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data)
def test_get_users_ok(self): client = APIClient() admin_user = User.objects.create_user( username='******', password='******', is_staff=True ) data = { 'username': '******', 'password': '******' } response = self.client.post( reverse('get-tokens'), data, format='json' ) token = response.data['access'] client.credentials(HTTP_AUTHORIZATION= 'Bearer ' + token) response = client.get( reverse('users') ) users = User.objects.all() serializer = UserListSerializer(users, many=True) self.assertEquals(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serializer.data)
def update(self, request, pk): user = get_object_or_404(UserDetail, pk=pk) self.check_object_permissions(request, user) serializer = self.get_serializer(instance=user, data=request.data, partial=True) upload_files_user = request.FILES.get('upload_image', None) if serializer.is_valid(): update_user = serializer.save() if upload_files_user is not None: session = Session(aws_access_key_id='AKIAJYDV7TEBJS6JWEEQ', aws_secret_access_key= '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') s3 = session.resource('s3') bucket = s3.Bucket('walladog') key_file = user.user.username + ".jpeg" bucket.put_object(ACL='public-read', Key=key_file, Body=upload_files_user, ContentType='image/jpeg') serialize_bnew_user = UserListSerializer(update_user) return Response(serialize_bnew_user.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request): serializer = self.get_serializer(data=request.data) upload_files_user = request.FILES.get('upload_image', None) if serializer.is_valid(): if upload_files_user is not None: session = Session(aws_access_key_id='AKIAJYDV7TEBJS6JWEEQ', aws_secret_access_key= '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') s3 = session.resource('s3') bucket = s3.Bucket('walladog') key_file = request.data['username'] + ".jpeg" bucket.put_object(ACL='public-read', Key=key_file, Body=upload_files_user, ContentType='image/jpeg') photo_url = "https://s3.amazonaws.com/walladog/" + key_file new_user = serializer.save(avatar_url=photo_url) else: new_user = serializer.save() serialize_bnew_user = UserListSerializer(new_user) return Response(serialize_bnew_user.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request): isPrivate = self.request.query_params.get('isprivate', None) events = [] if isPrivate == '1': stands = [] userName = request.user userId = UserListSerializer(User.objects.filter(login=userName), many=True).data[0]['id'] userStands = UserStandListSerializer( UserStand.objects.filter(owner=userId), many=True).data for userStand in userStands: stands.append( StandListSerializer( Stand.objects.filter(id=userStand['id']), many=True).data[0]) for stand in stands: events.append( EventListSerializer( Event.objects.filter(id=stand['eventId']), many=True).data[0]) uniqueEvents = [] for event in events: if event not in uniqueEvents: uniqueEvents.append(event) events = uniqueEvents else: events = Event.objects.all() events = EventListSerializer(events, many=True).data return Response(events, status=status.HTTP_200_OK)
class SubmissionCommentSerializer(serializers.ModelSerializer): created_by = UserListSerializer(read_only=True) class Meta: model = Comment fields = ('text', 'created_by', 'created_at', 'submission')
def post(self, request, *args, **kwargs): form = UserListForm(request.data) if not form.is_valid(): return Response(form.errors, status=status.HTTP_400_BAD_REQUEST) cld = form.cleaned_data _objects = self.get_objects_list(request, **kwargs) if isinstance(_objects, Exception): return Response({'detail': _objects.args}, status=status.HTTP_400_BAD_REQUEST) serializer = UserListSerializer(data=_objects) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) results = serializer.list_data(**cld) if isinstance(results, Exception): return Response({'Error': results.args}, status=status.HTTP_400_BAD_REQUEST) return Response(results, status=status.HTTP_200_OK)
class NeedSerializer(serializers.ModelSerializer): supporters = UserListSerializer(many=True, read_only=True) categories = CategoryListSerializer(many=True, read_only=True) class Meta: model = Need fields = ('id', 'title', 'description', 'address', 'end_date', 'is_fixed', 'categories', 'supporters')
def get(self, request): users = User.objects.all() # agregamos el paginador paginator = PageNumberPagination() paginated_users = paginator.paginate_queryset(users, request) # tenemos que devolver en el response datos primitivos integers, floats, booleans, tuples, lists, dictionaries, strings serializer = UserListSerializer(paginated_users, many=True) return paginator.get_paginated_response(serializer.data)
class CollectionDetailSerializer(serializers.ModelSerializer): # Сериализация для страницы коллекции movies = MovieListSerializer(many=True) owner = UserListSerializer() class Meta: model = Collection fields = "__all__"
class AuditLogSerializer(serializers.ModelSerializer): author = UserListSerializer() environment = EnvironmentSerializerLight() project = ProjectSerializer() class Meta: model = AuditLog fields = ('created_date', 'log', 'author', 'environment', 'project', 'related_object_id', 'related_object_type')
def my_followers(): user = current_identity page_size = request.args.get('page_size', 5) page = request.args.get('page', 1) following_ids = [ur.following_id for ur in UserSubscription.query.filter_by(follower_id=user.id).options(load_only('following_id')).all()] following = db.session.query(User).filter(User.id.in_(following_ids)).options(load_only('id', 'username')).paginate( page=page, per_page=page_size) return jsonify(UserListSerializer('following', following).get_data()), 200
class SuperUserListSerializer(serializers.ModelSerializer): user_obj = UserListSerializer(read_only=True, source='user') user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False, allow_null=True) profile_img = Base64ImageField(required=False, allow_null=True) class Meta: model = SuperUser fields = ('__all__')
def __init__(self, user_pagination_obj, following_ids, follower_ids): self.data = {} self.data['page_meta'] = PageSerializer(user_pagination_obj, serialize_items=False).data followers = [] following = [] for u in user_pagination_obj.items: if u.id in follower_ids: followers.append(u) elif u.id in following_ids: following.append(u) following_response = UserListSerializer('following', following).get_data() followers_response = UserListSerializer('followers', followers).get_data() self.data['followers'] = followers_response self.data['following'] = following_response
def list(self, request): """ Return a list of the system users :param request: HttpRequest :return: Response """ users = User.objects.all().values("id", "username") page = self.paginate_queryset(users) serializer = UserListSerializer(page, many=True) return self.get_paginated_response(serializer.data)
class ProductListSerializer(ModelSerializer): variations = VariationSerializer(many=True, required=False) user = UserListSerializer() class Meta: model = Product fields = ["pk", "title", "description", "tags", "variations", "user"] def get_description(self, obj): log.warning(f"Product Description: {obj.description}") return obj.description.split('.', 1)[0].split('\n', 1)[0]
def get(self, request): username_str = request.GET.get('username', None) if username_str: users = User.objects.filter( username__contains=username_str).order_by('username') #serializer = UserListSerializer(users, many=True) else: users = User.objects.all().order_by('username') #serializer = UserSerializer(users, many=True) serializer = UserListSerializer(users, many=True) return Response(serializer.data)
def update_role(self, request, organisation_pk, pk): user = self.get_object() organisation = Organisation.objects.get(pk=organisation_pk) user_organisation = user.get_user_organisation(organisation) serializer = self.get_serializer( instance=user_organisation, data=request.data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response( UserListSerializer(user, context={"organisation": organisation}).data )
def get(self, request): stands = [] userName = request.user userId = UserListSerializer(User.objects.filter(login=userName), many=True).data[0]['id'] userStands = UserStandListSerializer( UserStand.objects.filter(owner=userId), many=True).data for userStand in userStands: stands.append( StandOwnerListSerializer( Stand.objects.filter(id=userStand['standId']), many=True).data[0]) return Response(stands, status=status.HTTP_200_OK)
class EmployeeListSerializer(serializers.ModelSerializer): user_obj = UserListSerializer(read_only=True, source='user') user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False, allow_null=True) merchant_obj = MerchantListSerializer(read_only=True, source='merchant') merchant = serializers.PrimaryKeyRelatedField( queryset=Merchant.objects.all(), required=False, allow_null=True) profile_img = Base64ImageField(required=False, allow_null=True) class Meta: model = Employee fields = [ 'id', 'merchant', 'merchant_obj', 'user', 'user_obj', 'profile_img' ]
def list(self, request, club_pk=None, region_pk=None): # Our permission_classes setting for list actions means that # the user is either an admin or a dive officer. If the user # is an admin, we'll let them view the whole list of users; # otherwise, we'll filter to limit results to the DO's club. # Find the user making the request. user = self.request.user # Set the initial queryset. If the user is an admin, then # they can view the entire list. if user.is_staff: queryset = User.objects.all() # If the user is not an admin, then they're a DO; return # only the members of their club. else: queryset = User.objects.filter(club=user.club) if region_pk is not None: queryset = queryset.filter(club__region__id=region_pk) # If we are looking for the users within a specific club # (e.g., an admin has made the request), then filter further. if club_pk is not None: queryset = queryset.filter(club__id=club_pk) # Look at the request params. If they contain something useful, # then add it to the filter. params = request.query_params # The user can search for users by a substring that will be # compared case-insensitively to both the last and first # names in the database. We'll also do a preliminary check # to see whether it's numeric, in which case it could be a # CFT number. if 'name' in params: fragment = params['name'] if fragment.isdigit(): q = Q(username__icontains=fragment) else: q = Q(first_name__icontains=fragment) | Q( last_name__icontains=fragment) queryset = queryset.filter(q) # Serialize the queryset to JSON. serializer = UserListSerializer(queryset, many=True) # Return a Response. return Response(serializer.data)
class AuditLogSerializer(serializers.ModelSerializer): author = UserListSerializer() environment = EnvironmentSerializerLight() project = ProjectSerializer() class Meta: model = AuditLog fields = ( "created_date", "log", "author", "environment", "project", "related_object_id", "related_object_type", )
def get(self, request): standId = self.request.query_params.get('standid', None) isOwner = None matches = [] userName = request.user userId = UserListSerializer(User.objects.filter(login=userName), many=True).data[0]['id'] userStands = UserStandListSerializer( UserStand.objects.filter(owner=userId), many=True).data for userStand in userStands: if (str(userStand['standId']) == standId): isOwner = True if isOwner != None: matches = Match.objects.filter(standID=standId) matches = MatchListSerializer(matches, many=True).data return Response(matches, status=status.HTTP_200_OK)
def get(self, request): eventId = self.request.query_params.get('eventid', None) isPrivate = self.request.query_params.get('isprivate', None) stands = [] if isPrivate == '1': stands = [] userName = request.user userId = UserListSerializer(User.objects.filter(login=userName), many=True).data[0]['id'] userStands = UserStandListSerializer( UserStand.objects.filter(owner=userId), many=True).data for userStand in userStands: stands.append( StandListSerializer( Stand.objects.filter(id=userStand['id']), many=True).data[0]) else: stands = Stand.objects.filter(eventId=eventId) stands = StandListSerializer(stands, many=True).data return Response(stands, status=status.HTTP_200_OK)
class ListUserEnvironmentPermissionSerializer( CreateUpdateUserEnvironmentPermissionSerializer ): user = UserListSerializer()
def users(self, request, pk): organisation = self.get_object() users = organisation.users.all() return Response(UserListSerializer(users, many=True).data)
def list(self, request): users = User.objects.all() paginated_users = self.paginate_queryset(users) serializer = UserListSerializer(paginated_users, many=True) return self.get_paginated_response(serializer.data)