def get_user(request): user = User.objects.get(id=request.user.id) posts = Post.objects.filter(poster_ID=request.user.id) createdGroups = Group.objects.filter(created_by=request.user.id) groups = join.objects.filter(UID=request.user.id) postsSerializer = PostSerializer(posts, many=True) createdGroupsSerializer = CreatedGroupsSerializer(createdGroups, many=True) groupsSerializer = JoinedGroupsSerializer(groups, many=True) friends = Friends.objects.filter(FID=request.user.id, status="Friends") friendSerializer = FriendsSerializer(friends, many=True) responeDictionary = {} responeDictionary['username'] = user.username responeDictionary['email'] = user.email responeDictionary['gender'] = user.profile.gender responeDictionary['birth_date'] = user.profile.birth_date responeDictionary['profileImg'] = str(user.profile.profileImg) responeDictionary['friends'] = friendSerializer.data responeDictionary['posts'] = postsSerializer.data responeDictionary['createdGroups'] = createdGroupsSerializer.data responeDictionary['groups'] = groupsSerializer.data return JsonResponse({'data': responeDictionary}, safe=False, status=status.HTTP_200_OK)
def get(self, request, *args, **kwargs): """ Get paginated post search results. <BASE_URL>/<endpoint>/[..query_params] Available query_params options: 1. page_number [int, default 1] 2. page_size [int, default 50] 3. search [str] misco.com/post/search/?search=martial%20arts&page_size=100 """ page_number = request.query_params.get('page_number', 1) page_size = request.query_params.get('page_size', 50) search_token = request.query_params.get('search', None) if not search_token: raise Exception('Search Token not provided.') posts = Post.objects.filter( description__icontains=search_token ).exclude( is_pornographic=True ) paginator = Paginator(posts, page_size) serializer = PostSerializer( paginator.page(page_number), many=True, context={'request': request} ) response = Response(serializer.data, status=status.HTTP_200_OK) return response
def api_create_post_view(request): if request.method == "POST": serializer = PostSerializer(data=request.data) 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 create_view(request): print(request.POST.get('title')) data = JSONParser().parse(request) serialization = PostSerializer(data=data) if serialization.is_valid(): serialization.save() return JsonResponse(serialization.data, safe=False, status = 201) return JsonResponse(serialization.errors, safe=False, status=400)
def detailPost(request, slug): try: posts = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = PostSerializer(posts) return Response(serializer.data, status=status.HTTP_200_OK)
class FavoritePostSerializer(ModelSerializer): """Serializer for favorite posts.""" post = PostSerializer() profile = ProfileSerializer() class Meta: model = FavoritePost fields = ('post', 'profile')
class CommentSerializer(serializers.ModelSerializer): """Serializer class for comment model.""" post = PostSerializer() profile = ProfileSerializer() class Meta: model = Comment fields = ('post', 'profile', 'comment', 'created_at')
def api_detail_post_view(request, slug): try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = PostSerializer(post) return Response(serializer.data)
def detail_view(request, pk): queryset = Post.objects.get(pk=pk) # for obj in queryset: # print(obj) # print(Post.objects.get(pk=pk)) # print(Post.objects.filter(pk=pk)) serialization = PostSerializer(queryset) print('Serialization ', serialization.data) return JsonResponse(serialization.data, safe=False)
def get(self, request, *args, **kwargs): """Get the paginated timeline for authenticated user.""" page_number = request.query_params.get('page_number', 1) page_size = request.query_params.get('page_size', 100) posts = TimelineCentral().posts(request) if not posts: raise Exception('There are no posts for you to see.') paginator = Paginator(posts, page_size) serializer = PostSerializer(paginator.page(page_number), many=True, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK)
def get_post_api(request, *args, **kwargs): post_id = request.GET.get("id") if post_id is None: return Response({"error": "Post id is required"}, status=400) try: post = Post.objects.get(id=post_id) except Post.DoesNotExist: return Response({"error": f"Post with id - {post_id} does not exist"}, status=400) serializer = PostSerializer(instance=post) return Response(serializer.data, status=200)
def get_friend(request, username): user = User.objects.get(username=username) posts = Post.objects.filter(poster_ID=user.id) createdGroups = Group.objects.filter(created_by=user.id) groups = join.objects.filter(UID=user.id) postsSerializer = PostSerializer(posts, many=True) createdGroupsSerializer = CreatedGroupsSerializer(createdGroups, many=True) groupsSerializer = JoinedGroupsSerializer(groups, many=True) friends = Friends.objects.filter(UID=user.id) friendSerializer = FriendsSerializer(friends, many=True) criterion1 = Q(UID=request.user.id) criterion2 = Q(FID=user.id) criterion3 = Q(FID=request.user.id) criterion4 = Q(UID=user.id) areTheyFriends = Friends.objects.filter(criterion1 & criterion2 | criterion3 & criterion4).count() responeDictionary = {} if areTheyFriends == 0: responeDictionary['friends'] = "Strangers" elif areTheyFriends == 2: responeDictionary['friends'] = "Friends" else: areTheyFriends = Friends.objects.filter(criterion1 & criterion2).count() if areTheyFriends == 1: responeDictionary['friends'] = "Sent" else: responeDictionary['friends'] = "Pending" responeDictionary['username'] = user.username responeDictionary['email'] = user.email responeDictionary['gender'] = user.profile.gender responeDictionary['birth_date'] = user.profile.birth_date responeDictionary['profileImg'] = str(user.profile.profileImg) # responeDictionary['friends'] = friendSerializer.data # for x in friendSerializer.data: # if request.user.username == x['FriendName']: # friends_status = x['status'] # break # else: # friends_status = 'not friends' # responeDictionary['friends_status'] = friends_status responeDictionary['posts'] = postsSerializer.data responeDictionary['createdGroups'] = createdGroupsSerializer.data responeDictionary['groups'] = groupsSerializer.data return JsonResponse({'data': responeDictionary}, safe=False, status=status.HTTP_200_OK)
def api_update_post_view(request, slug): try: post = Post.objects.get(slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "PUT": serializer = PostSerializer(post, data=request.data) data = {} if serializer.is_valid(): serializer.save() data["success"] = "udpate successful" return Response(data=data) return Response(serializer.errors, status=status.HTTP_404_BBAD_REQUEST)
def patch(self, request, *args, **kwargs): id_ = self.kwargs.get('id') object_to_update = Post.objects.filter(id=id_).first() print("object_to_update", object_to_update) # try: # object_to_update = Post.objects.get(pk=pk) # except Post.DoesNotExist: # object_to_update= None serializer = PostSerializer(object_to_update, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(code=201, data=serializer.data, safe=False) return JsonResponse(code=400, data="Wrong Parameters", safe=False)
def get(self, request, username): """Get all posts liked by the user.""" posts = Post.objects.filter( profile__user__username=username ).annotate( num_likes=Count('activity') ).order_by('-created_at') serialized = PostSerializer( posts, many=True, context={'request': request} ) return Response( serialized.data, status=status.HTTP_200_OK )
def get(self, request, sound_id): """Return all posts by same sound.""" posts = Post.objects.filter( sound__uuid=sound_id ).annotate( num_likes=Count('activity') ).order_by('-num_likes')[:100] serializer = PostSerializer( posts, many=True, context={'request': request} ) return Response( serializer.data, status=status.HTTP_200_OK )
def get(self, request, username): """Get all videos for a profile.""" page_number = request.query_params.get('page_number', 1) page_size = request.query_params.get('page_size', 50) posts = Post.objects.filter( profile__user__username=username ) paginator = Paginator(posts, page_size) serialized = PostSerializer( paginator.page(page_number), many=True, context={'request': request} ) return Response( data=serialized.data, status=status.HTTP_200_OK )
def main_view(request, pk): if request.method == 'GET': print('GET') return HttpResponse('GET METHOD') if request.method == 'POST': data = JSONParser().parse(request) serialization = PostSerializer(data=data) if serialization.is_valid(): serialization.save() return JsonResponse(serialization.data, safe=False, status = 201) return JsonResponse(serialization.errors, safe=False, status=400) if request.method == 'DELETE': print('DELETE') post = get_object_or_404(Post, pk=pk) # print(Post.objects.get(pk=pk)) # Post.objects.get(pk=pk).delete() post.delete() return HttpResponse(status=204)
def get(self, request, *args, **kwargs): """Get all trending posts based on tags.""" popular_hashtags = Hashtag.objects.all().order_by('-count')[:20] response = {} for hashtag in popular_hashtags: posts = Post.objects.filter( uuid__in=HashtagLink.objects.filter( hashtag=hashtag ).values_list( 'post__uuid', flat=True ) ).annotate( num_likes=Count('activity') ).order_by('-num_likes')[:10] response[hashtag.name] = PostSerializer( posts, many=True, context={'request': request} ).data return Response( data=response, status=status.HTTP_200_OK )
def get(self, request, tag): """Get posts of the same tag.""" page_number = request.query_params.get('page_number', 1) page_size = request.query_params.get('page_size', 50) tag = Hashtag.objects.get(name=tag.lower()) posts = Post.objects.filter( uuid__in=HashtagLink.objects.filter( hashtag=tag ).values_list( 'post__uuid', flat=True ) ).annotate( num_likes=Count('activity') ).order_by('-num_likes') paginator = Paginator(posts, page_size) serialized_posts = PostSerializer( paginator.page(page_number), many=True, context={'request': request} ) return Response( serialized_posts.data, status=status.HTTP_200_OK )
def get(self, request): serializer = PostSerializer(request.post)
def post_details(self): return PostSerializer(self.post).data
def get_main_posts_api(request, *args, **kwargs): posts = get_5_random_posts() serializer = PostSerializer(instance=posts, many=True) return Response(serializer.data, status=200)
def get(self, request, pk, format=None): print("API: Get Selected Post") post = get_object_or_404(Post.objects.get_posts(), id=pk) serializer = PostSerializer(post) return Response(serializer.data)
def postsListAPI(request): experience = Post.objects.order_by("-date_updated") serializer = PostSerializer(experience, many=True) return Response(serializer.data)
class TagWithPostsSerializer(serializers.ModelSerializer): posts = PostSerializer(many=True) class Meta: model = Tag fields = ["name", "posts"]
def get_posts(qs): from posts.api.serializers import PostSerializer return PostSerializer(qs, many=True).data
def list_view(request): queryset = Post.objects.all() print('Posts', queryset) serialization = PostSerializer(queryset, many=True) print('Serialization ', serialization.data) return JsonResponse(serialization.data, safe=False)
def list(self, request, pk): print("API: Get Public Profile Post List") queryset = get_list_or_404(self.get_queryset().filter(user=pk)) serializer = PostSerializer(queryset, many=True) return Response(serializer.data)