Beispiel #1
0
   def tags(self, request, pk=None):
      publicacion = self.get_object()

      if request.method == 'GET':
         serializer = TagSerializer(publicacion.tag, many=True)
         return Response(status=status.HTTP_200_OK, data=serializer.data)

      if request.method == 'POST':
         tag_id = request.data['tags_ids']

         for id_ta in tag_id:
            tag_encontrado = Tag.objects.get(id=id_ta)
            publicacion.tag.add(tag_encontrado)

         serializer = TagSerializer(publicacion.tag, many=True)
         return Response(status=status.HTTP_201_CREATED, data=serializer.data)

      if request.method == 'DELETE':
         tag_id = request.data['tags_ids']

         for id_ta in tag_id:
            tag_encontrado = Tag.objects.get(id=id_ta)
            publicacion.tag.remove(tag_encontrado)

         serializer = TagSerializer(publicacion.tag, many=True)
         return Response(status=status.HTTP_400_BAD_REQUEST, data=serializer.data)
Beispiel #2
0
    def tags(self, request, pk=None):

        publicacion = self.get_object()
        if request.method == 'GET':
            serialized = TagSerializer(publicacion.tags, many=True)
            return Response(status=status.HTTP_200_OK, data=serialized.data)

        if request.method == 'POST':
            tag = {
                "nombre": request.data['nombre'],
                "publicaciones": [publicacion.id]
            }
            serialized = TagSerializer(data=tag)
            if serialized.is_valid():
                serialized.save()
                return Response(status=status.HTTP_200_OK,
                                data=serialized.data)
            else:
                return Response(status=status.HTTP_200_OK,
                                data=serialized.errors)

        if request.method == 'DELETE':
            tag_id = request.data['id']
            tag = Tag.objects.get(id=tag_id)
            tag.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
class UserProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    tags = TagSerializer(many=True)

    class Meta:
        model = UserProfile
        fields = ('id', 'username', 'tags', 'location_count')
Beispiel #4
0
class PublicacionSerializer(serializers.ModelSerializer):
    #relacion de muchos a muchos (read_only=True, many=True)
    comentarios = ComentarioSerializer(read_only=True, many=True)
    tag = TagSerializer(read_only=True, many=True)
    class Meta :
        model = Publicacion
        fields = '__all__'
class OrderSerializer(serializers.ModelSerializer):

    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Order
        fields = "__all__"
Beispiel #6
0
class MediaSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Media
        read_only_fields = (
            "id",
            "uploaded_on",
            "uploaded_by",
            "url",
            "association",
            "mimetype",
            "tags",
        )
        fields = read_only_fields + ("name", "description")

    def to_representation(self, instance):
        res = super(MediaSerializer, self).to_representation(instance)

        # Convert the server URI to an absolute URL
        # ie /media/file.txt -> https://domain.name/media/file.txt
        request = self.context["request"]
        if request:
            host = request.get_host()
            res["url"] = f"{'https' if request.is_secure() else 'http'}://{host}{res['url']}"

        return res
class MediaSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Media
        read_only_fields = (
            "id",
            "uploaded_on",
            "uploaded_by",
            "url",
            "preview_url",
            "preview_large_url",
            "association",
            "mimetype",
            "tags",
        )
        fields = read_only_fields + ("name", "description")

    def to_representation(self, instance):
        res = super(MediaSerializer, self).to_representation(instance)

        # Convert the server URI to an absolute URL
        # ie /media/file.txt -> https://domain.name/media/file.txt
        request = self.context["request"]
        if request:
            res["url"] = urlize(request, res["url"]) if res["url"] else ""
            res["preview_url"] = urlize(request, res["preview_url"])
            res["preview_large_url"] = urlize(request, res["preview_large_url"])
        return res
Beispiel #8
0
class NewsletterSerializer(serializers.ModelSerializer):
    tag = TagSerializer(read_only=True)
    users = UserSerializer(read_only=True, many=True)
    author = UserSerializer(read_only=True)

    class Meta:
        model = Newsletter
        fields = '__all__'
Beispiel #9
0
 def post(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     tag = serializer.save()
     return Response({
         "tag":
         TagSerializer(tag, context=self.get_serializer_context()).data,
     })
Beispiel #10
0
class MemesSerializer(serializers.ModelSerializer):
    owner = UserSerializer(many=True, read_only=True)
    tags = TagSerializer(many=True, read_only=True)

    class Meta:
        model = Memes
        fields = '__all__'
        depth = 1
class IndexPostListSerializer(serializers.HyperlinkedModelSerializer, EagerLoaderMixin):
    """
    首页帖子列表序列化器
    """
    author = serializers.SerializerMethodField()
    reply_count = serializers.SerializerMethodField()
    tags = TagSerializer(many=True, read_only=True)
    latest_reply_time = serializers.SerializerMethodField()

    SELECT_RELATED_FIELDS = ['author']
    PREFETCH_RELATED_FIELDS = [
        'tags',
        Prefetch('replies', queryset=Reply.objects.order_by('-submit_date'))
    ]

    class Meta:
        model = Post
        fields = (
            'id',
            'url',
            'title',
            'views',
            'created',
            'modified',
            'latest_reply_time',
            'pinned',
            'highlighted',
            'tags',
            'author',
            'reply_count',
        )

    def get_author(self, obj):
        author = obj.author
        request = self.context.get('request')
        url = author.mugshot.url
        return {
            'id': author.id,
            'mugshot': request.build_absolute_uri(url) if request else url,
            'nickname': author.nickname,
        }

    def get_reply_count(self, obj):
        """
        返回帖子的回复数量
        """
        return obj.replies.count()

    def get_latest_reply_time(self, obj):
        """
        返回最后一次评论的时间,
        如果没有评论,返回null
        """
        replies = obj.replies.all()
        if replies:
            return replies[0].submit_date
        else:
            return None
 def put(self, request, pk, format=None):
     tag = self.get_object(pk=pk)
     serializer = TagSerializer(tag, data=request.data)
     if serializer.is_valid():
         if request.user.is_superuser:
             serializer.save()
             return Response(serializer.data, status=status.HTTP_200_OK)
         else:
             return Response(status=status.HTTP_401_UNAUTHORIZED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Beispiel #13
0
    def test_expected_fields(self):
        """Tests expected serializer fields
        name, is_public
        (id and url are for HyperlinkedModelSerializer, not included in validated_data.keys())
        """
        tag_data = factory.build(dict, FACTORY_CLASS=TagFactory)
        serializer = TagSerializer(data=tag_data, context={'request': None})
        is_valid = serializer.is_valid()

        print("Errors: ", serializer.errors)
        assert is_valid, "serializer validation test"
        assert serializer.validated_data.keys() == set(['name', 'is_public'])
class DisplayedEventConditionSerializer(serializers.ModelSerializer):
    stage = StageSerializer(required=False)
    task_type = TaskTypeSerializer(required=False)
    task_status = TaskStatusSerializer(required=False)
    event_tags = TagSerializer(required=False, many=True)

    class Meta:
        model = EventCondition

        fields = ('id', 'name', 'task_type', 'task_status', 'stage',
                  'event_condition_type', 'event_condition_category', 'hook',
                  'params', 'event_tags', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')
Beispiel #15
0
    def create(self, request, *args, **kwargs):
        if "namespace" in request.data and "value" in request.data:
            try:
                tag = Tag.objects.get(
                    namespace=request.data.get("namespace"),
                    value=request.data.get("value"),
                )
                return Response(TagSerializer().to_representation(tag),
                                status=201)
            except Tag.DoesNotExist:
                pass

        return super(TagViewSet, self).create(request, *args, **kwargs)
class ProjectSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, required=False)

    class Meta:
        model = Project
        fields = ('id', 'user', 'name', 'description', 'tags', 'table_id')

    def create(self, validated_data):
        tag_data = validated_data.pop('tags')
        project = Project.objects.create(**validated_data)

        for tag in tag_data:
            tag, created = Tag.objects.get_or_create(name=tag['name'],
                                                     slug=tag['slug'])
            project.tags.add(tag)
        return project
Beispiel #17
0
class PostSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')
    tags_details = TagSerializer(source='tags', read_only=True, many=True)
    api_url = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'title', 'description', 'created_on', 'author',
                  'tags_details', 'url', 'api_url', 'image', 'counter')
        read_only_fields = ('id', 'created_on', 'slug')
        lookup_field = 'slug'
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

    def get_api_url(self, obj):
        return "#/post/%s" % obj.slug
Beispiel #18
0
class ArticleSerializer(serializers.ModelSerializer):
    author = SmallUserSerializer(required=False, read_only=True)
    total_price = serializers.SerializerMethodField()
    date = serializers.SerializerMethodField()
    tag = TagSerializer(read_only=True)

    def get_total_price(self, obj):
        return obj.quantity * obj.price

    def get_date(self, obj):
        return obj.invoice.date

    class Meta:
        model = Article
        fields = ['id', 'created', 'updated', 'item', 'quantity', 'price', 'tag', 'invoice', 'author', 'date',
                  'total_price']
        read_only_fields = ['author']
Beispiel #19
0
    def publicacion(self, request, pk=None):
        tag = self.get_object()
        if request.method == 'GET':
            serializer = TagSerializer(tag.publicacion, many=True)
            return Response(status=status.HTTP_200_OK, data=serializer.data)

        if request.methos == 'POST':
            publicacion_id = request.data['publicacion_id']
            for publicaciones in publicacion_id:
                publicacion = Publicacion.objects.get(id=int(publicaciones))
                tag.publicacion.add(publicacion)
                return Response(status=status.HTTP_200_OK)
        if request.methos == 'DELETE':
            publicacion_id = request.data['publicacion_id']
            for publicaciones in publicacion_id:
                publicacion = Publicacion.objects.get(id=int(publicaciones))
                tag.publicacion.remove(publicacion)
                return Response(status=status.HTTP_200_OK)
Beispiel #20
0
    def get_products(self, request):
        p_type = self.request.query_params.get('type', None)
        if not p_type:
            return Response(data="Must specify a product type.", status=status.HTTP_400_BAD_REQUEST)
        cards = Product.objects.filter(p_type=p_type)
        page = self.paginate_queryset(cards)

        tags = Tag.objects.filter(product__in=cards).distinct()

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            res_data = {
                'cards': ProductSerializer(page, many=True).data,
                'tags': TagSerializer(tags, many=True).data
            }
            return Response(data=res_data)
        
        serializer = self.get_serializer(page, many=True)
        return Response(serializer.data)
Beispiel #21
0
    def tags(self, request, pk=None):
        newsletter = self.get_object()
        if request.method == 'GET':
            serialized = TagSerializer(newsletter.tags, many=True)
            return Response(status=status.HTTP_200_OK, data=serialized.data)

        if request.method == 'POST':
            newsletter_id = request.data['tags']
            for tag_id in newsletter_id:
                tag = Tag.objects.get(id=int(tag_id))
                newsletter.tags.add(tag)
            return Response(status=status.HTTP_201_CREATED)

        if request.method == 'DELETE':
            newsletter_id = request.data['tags']
            for tag_id in newsletter_id:
                tag = Tag.objects.get(id=int(tag_id))
                newsletter.tags.remove(tag)
            return Response(status=status.HTTP_204_NO_CONTENT)
Beispiel #22
0
    def tags(self, request, pk=None):
        publica = self.get_object()
        if request.method == 'GET':
            serializer = TagSerializer(publica.tags, many=True)
            return Response(status=status.HTTP_200_OK, data=serializer.data)

        if request.method == 'POST':
            tags_id = request.data['tags_ids']
            print(tags_id)
            for tag_id in tags_id:
                tag = Tag.objects.get(id=int(tag_id))
                publica.tags.add(tag)

            return Response(status=status.HTTP_200_OK)

        if request.method == 'DELETE':
            tags_id = request.data['tags_ids']
            print(tags_id)
            for tag_id in tags_id:
                tag = Tag.objects.get(id=int(tag_id))
                publica.tags.remove(tag)

            return Response(status=status.HTTP_200_OK)
Beispiel #23
0
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    tags = TagSerializer(many=True)
    user = SmallUserSerializer()

    has_perm = serializers.SerializerMethodField()

    def get_has_perm(self, document):
        user = self.context['request'].user
        return user.write_perm(obj=document)

    class Meta:
        model = Document
        fields = ('id', 'name', 'url', 'group', 'description', 'user', 'pages',
                  'date', 'views', 'downloads', 'state', 'md5', 'tags',
                  'has_perm')

        extra_kwargs = {
            'user': {
                'lookup_field': 'netid'
            },
            'group': {
                'lookup_field': 'slug'
            },
        }
 def post(self, request, format=None):
     serializer = TagSerializer(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)
Beispiel #25
0
 def get_tags(self, post):
     serializer = TagSerializer(post.tags, many=True)
     return serializer.data
Beispiel #26
0
class LinkSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, required=False, read_only=True)

    class Meta:
        model = Link
        fields = ('id', 'url', 'image_url', 'title', 'description', 'content_url', 'tags', )
Beispiel #27
0
class DocumentSerializer(serializers.HyperlinkedModelSerializer):
    tags = TagSerializer(read_only=True, many=True)

    user = SmallUserSerializer(read_only=True)

    user_vote = serializers.SerializerMethodField(read_only=True)
    has_perm = serializers.SerializerMethodField(read_only=True)
    file_size = serializers.SerializerMethodField(read_only=True)

    original_url = serializers.HyperlinkedIdentityField(
        view_name='document-original',
    )

    pdf_url = serializers.HyperlinkedIdentityField(
        view_name='document-pdf',
    )

    class Meta:
        model = Document

        read_only_fields = (
            'course', 'date', 'downloads', 'file_size',
            'file_type', 'has_perm', 'id', 'is_processing',
            'is_ready', 'is_unconvertible', 'md5', 'pages', 'state',
            'url', 'user', 'user_vote', 'views', 'votes',
            'original_url', 'pdf_url', 'imported',
        )
        writable_fields = (
            'description', 'name', 'tags'
        )

        fields = writable_fields + read_only_fields

        extra_kwargs = {
            'user': {'lookup_field': 'netid'},
            'course': {'lookup_field': 'slug'},
        }

    def get_user_vote(self, document):
        user = self.context['request'].user
        # We do the filtering in python as this method is called from REST with all the necessary
        #   data already prefetched. Using self.vote_set.filter() would lead to another roundtrip
        #   to the database for each document. Thats bad.
        users_vote = None
        for vote in document.vote_set.all():
            if vote.user == user:
                users_vote = vote
                break

        if users_vote is None:
            return 0
        elif users_vote.vote_type == Vote.UPVOTE:
            return 1
        elif users_vote.vote_type == Vote.DOWNVOTE:
            return -1
        else:
            raise NotImplemented("Vote not of known type.")

    def get_has_perm(self, document):
        user = self.context['request'].user
        return user.write_perm(obj=document)

    def get_file_size(self, document):
        try:
            return document.original.size
        except (FileNotFoundError, NoSuchKey):
            return None
Beispiel #28
0
 def tags(self, request, pk=None):
     project = self.get_object()
     serializer = TagSerializer(project.tags, many=True)
     return Response(serializer.data)
 def get(self, request, format=None):
     tags = Tag.objects.all()
     serializer = TagSerializer(tags, many=True)
     return Response(serializer.data)
 def get(self, request, pk, format=None):
     tag = self.get_object(pk)
     serializer = TagSerializer(tag)
     return Response(serializer.data)