Ejemplo n.º 1
0
 def get(self, request: WSGIRequest):
     photos = Photo.objects.all().order_by('-shot_date')
     if request.GET.get('page'):
         page = self.paginator.paginate_queryset(photos, request)
         serializer = PhotoSerializer(page, many=True)
         return self.paginator.get_paginated_response(serializer.data)
     else:
         serializer = PhotoSerializer(photos, many=True)
         return Response(serializer.data)
Ejemplo n.º 2
0
class AlbumSerializer(serializers.ModelSerializer):
    """Album serializer class"""

    photos = PhotoSerializer(many=True, read_only=True)
    preview = PhotoSerializer(read_only=True)

    class Meta:
        """Meta class for Album serializer"""

        model = Album
        fields = ("id", "name", "description", "photos", "preview")
Ejemplo n.º 3
0
    def test_photo_detail(self):
        """
        Ensure we can view photo detail by id
        """
        photo = self.create_photo_model()
        response = self.make_request('get', 'retrieve', pk=photo.id)
        response_json = PhotoSerializer(photo).data

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn(
            response_json.pop("photo"),
            response.data.pop("photo")
        )
        self.assertEqual(response.data, response_json)
Ejemplo n.º 4
0
class RestaurantSerializer(serializers.ModelSerializer):
    photos = PhotoSerializer(many=True, read_only=True)
    city = CitySerializer(many=False, read_only=True)
    photo_header = serializers.SerializerMethodField(read_only=True)
    cook_types = CookTypeSerializer(many=True, read_only=True)
    rating = RatingSerializer(many=False, read_only=True)
    today_hours = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Restaurant
        fields = "__all__"

    def get_photo_header(self, restaurant):
        if restaurant.main_photo and restaurant.main_photo.url:
            return restaurant.main_photo.url
        photo = restaurant.photos.filter(url__isnull=False).first()
        if photo:
            return photo.url
        return None

    def get_today_hours(self, restaurant):
        weekday = MATCHING_DAYS[date.today().weekday()]
        return [
            OpenHoursSerializer(oh).data
            for oh in restaurant.open_hours.filter(week_day=weekday)
        ]
    def test_serialize_photo(self):
        """Assert Photo model instances are serialized as expected"""
        # Get serialized data
        all_photos = Photo.objects.all().order_by('-shot_date')
        serialized_data = PhotoSerializer(all_photos, many=True).data

        # Compare with test data
        self.photo_data_check(serialized_data)
Ejemplo n.º 6
0
class PostSerializer(serializers.ModelSerializer):
    images = PhotoSerializer(many=True, read_only=True, source='photo_posts')
    tags = serializers.ListField(child=serializers.CharField(max_length=12),
                                 write_only=True,
                                 required=False)
    _tags = TagShowSerializer(many=True, read_only=True, source='tagged_posts')
    user = PostingProfileSerializer(source='user.userprofile', read_only=True)

    class Meta:
        model = Post
        fields = [
            'id', 'post_text', 'time_stamp', 'images', 'like_count', 'tags',
            '_tags', 'user'
        ]
        read_only_fields = ('id', 'time_stamp', 'images', 'like_count', 'user')

    def create(self, validated_data):
        if validated_data.get('tags'):
            obj_id_list = []
            for name in validated_data['tags']:
                obj, _ = HashTag.objects.update_or_create(name=name)
                obj_id_list.append(obj.id)

            validated_data.pop('tags')
            post = Post.objects.create(**validated_data)

            data = {'post': post.id, 'tag': {*obj_id_list}}
            # validate unique-together
            serializer = TagPostListSerializer(data=data)
            serializer.is_valid(raise_exception=True)

            for obj_id in obj_id_list:
                tag = HashTag.objects.get(id=obj_id)
                TagPostList.objects.create(post=post, tag=tag)
        else:
            post = Post.objects.create(**validated_data)
        return post

    def update(self, instance, validated_data):
        if validated_data.get('tags'):
            obj_id_list = []

            for name in validated_data['tags']:
                obj, _ = HashTag.objects.update_or_create(name=name)
                obj_id_list.append(obj.id)

            validated_data.pop('tags')

            for obj_id in obj_id_list:
                tag = HashTag.objects.get(id=obj_id)
                TagPostList.objects.get_or_create(post=instance, tag=tag)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        return instance
Ejemplo n.º 7
0
    def test_get_all_photos(self):
        """Assert the Response of all photos is created and returned"""
        photos = Photo.objects.all().order_by('-shot_date')
        serializer = PhotoSerializer(photos, many=True)

        factory = APIRequestFactory()
        request = factory.get('/photos')

        views_response = 'photos.views.Response'
        self.mock_response_check(views_response, request, serializer)
Ejemplo n.º 8
0
def populate_data_to_groups_and_photos(user, parameter, photo_list):

    group_data = get_data_through_parameter("flickr.groups.getInfo",
                                            "group_id", parameter)
    group_name = group_data["group"]["name"]["_content"]
    dict_for_group = {
        "group_id": parameter,
        "group_name": group_name,
        "user": user.id
    }
    group_serializer = GroupSerializer(data=dict_for_group)
    if not group_serializer.is_valid():
        return group_serializer.errors, status.HTTP_400_BAD_REQUEST
    group_object = group_serializer.save()
    for object in photo_list:
        object["group"] = group_object.group_id
    photo_serializer = PhotoSerializer(
        data=photo_list, many=True)  #bulk create for photos under teh group
    if not photo_serializer.is_valid():
        return photo_serializer.errors, status.HTTP_400_BAD_REQUEST
    photo_serializer.save()
    return GroupSerializer(group_object).data, status.HTTP_201_CREATED
Ejemplo n.º 9
0
 def feed(self, request, pk):
     """
     Get photo feed for photographer, giving them a queryset of Photos
     near their location, and uploaded by photographers they are following.
     """
     photographer = Photographer.objects.get(id=pk)
     photo_feed = (Photo.objects.filter(
         Q(location__istartswith=photographer.location)
         | Q(uploaded_by__in=photographer.following.all())).exclude(
             uploaded_by=photographer))
     serializer = PhotoSerializer(photo_feed,
                                  many=True,
                                  context={'request': request})
     return Response(serializer.data)
Ejemplo n.º 10
0
 def put(self, request, pk, format=None):
     photo = self.get_object(pk)
     serializer = PhotoSerializer(photo,
                                  data=request.data,
                                  partial=True,
                                  context={'request': request})
     if serializer.is_valid():
         # Only allow update captions and status from draft to publish
         if 'captions' in request.data:
             serializer.save()
             return Response(serializer.data, status=status.HTTP_200_OK)
         elif 'status' in request.data:
             if request.data['status'] == 'p':
                 serializer.save(published_at=timezone.now())
             else:
                 serializer.save()
             return Response(serializer.data, status=status.HTTP_200_OK)
         else:
             return Response({'error': 'only allow captions and status'},
                             status=status.HTTP_400_BAD_REQUEST)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 11
0
    def post(self, request, format=None):
        photo_serializer = PhotoSerializer(data=request.data,
                                           context={'request': request})

        if photo_serializer.is_valid():
            # Add published_at if status=p
            if request.data['status'] == 'p':
                photo_serializer.save(user=self.request.user,
                                      published_at=timezone.now())
            else:
                photo_serializer.save(user=self.request.user)
            return Response(photo_serializer.data,
                            status=status.HTTP_201_CREATED)
        return Response(photo_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 12
0
    def get_photos_page_check(self, photos: Union[List[Photo], QuerySet],
                              page: str):
        """Assert the Response of the indicated page of photos
        is correctly created and returned"""
        page_size = PhotoCatalog.paginator.page_size
        PhotoCatalog.paginator.page_size = 1

        serializer = PhotoSerializer(photos, many=True)

        factory = APIRequestFactory()
        request = factory.get(f'/photos?page={page}')
        # Update the request to behave like a DRF Request
        request.query_params = request.GET

        views_response = 'photos.views.PhotoCatalog.paginator.get_paginated_response'
        self.mock_response_check(views_response, request, serializer)

        PhotoCatalog.paginator.page_size = page_size
Ejemplo n.º 13
0
    def get(self, request, format=None):
        # Filter by query params | ?status=p
        photo_status = request.query_params.get('status', None)
        if photo_status:
            photos = Photo.objects.filter(user=request.user.id,
                                          status=photo_status)
        else:
            photos = Photo.objects.filter(user=request.user.id)

        # Filter by query params | ?sort=asc/desc
        allowed_sort = ['asc', 'desc']
        sort = request.query_params.get('sort', None)
        if sort in allowed_sort:
            column = 'published_at' if sort == 'asc' else '-published_at'
            photos = photos.order_by(column)

        photo_serializer = PhotoSerializer(photos,
                                           many=True,
                                           context={'request': request})
        return Response(photo_serializer.data, status=status.HTTP_200_OK)
Ejemplo n.º 14
0
 def get(self, request, pk, format=None):
     photo = self.get_object(pk)
     serializer = PhotoSerializer(photo, context={'request': request})
     return Response(serializer.data)
Ejemplo n.º 15
0
 def get(self, request, gid):
     group = Group.objects.get(name=gid)
     queryset = Photo.objects.filter(group=group)
     serializer = PhotoSerializer(queryset, many=True)
     return Response(serializer.data)