예제 #1
0
 def to_internal_value(self, value):
     if isinstance(value, dict) and len(value) > 0:
         if not value.get('user', False):
             raise serializers.ValidationError('Invalid tag data.')
         try:
             user = get_user_model().objects.get(id=value.get('user', ''))
             value['user'] = user.id
             serializer = TagSerializer(data=value)
             if serializer.is_valid(raise_exception=True):
                 new_tag = serializer.save()
                 return new_tag
             else:
                 raise serializers.ValidationError('Invalid tag data.')
         except KeyError:
             raise serializers.ValidationError('id is a required field.')
         except ValueError:
             raise serializers.ValidationError('id must be an integer.')
         except ObjectDoesNotExist:
             raise serializers.ValidationError(
                 'User in tag does not exist.')
     if isinstance(value, (str, int)):
         try:
             return Tag.objects.get(id=value)
         except KeyError:
             raise serializers.ValidationError('id is a required field.')
         except ValueError:
             raise serializers.ValidationError('id must be an integer.')
         except ObjectDoesNotExist:
             raise serializers.ValidationError('Obj does not exist.')
class TransactionSerializer(serializers.ModelSerializer):

    tags = TagSerializer(many=True)

    class Meta:
        model = Transaction
        fields = "__all__"
        read_only_fields = ["user"]

    def create(self, validated_data):
        
        user = self.context['request'].user

        transaction = Transaction.objects.create(
            user=user,
            title=validated_data.get('title'),
            body=validated_data.get('body', validated_data.get('title')),
            amount=validated_data.get("amount"),
            transaction_type=validated_data.get("transaction_type"),
            currency=validated_data.get("currency", user.user_profile.currency)
        )

        for tag in validated_data.get('tags'):

            # check if tag exists or not
            _tag = Tag.objects.filter(name=tag['name'], created_by=self.context['request'].user).first()
            
            # if tag not exist, create one
            if not _tag:
                _tag = Tag.objects.create(name=tag['name'], created_by=self.context['request'].user)
            
            # now attach it with the transaction
            transaction.tags.add(_tag)
        return transaction
예제 #3
0
    def post(self, request, *args, **kwargs):
        user = request.user
        data = request.data
        # course = get_object_or_404(Course, pk=kwargs.get("pk"))
        tags = data

        object_model = kwargs.get('obj_model')
        model = ContentType.objects.get(model=object_model)
        object_id = kwargs.get("obj_pk")
        response = []
        for tag in tags:
            t = Tag.objects.filter(url=tag['url']).first()
            if not t:

                serializer = TagSerializer(data=tag)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                t = serializer.instance
            et = EntityTag.objects.filter(tag=t.pk,
                                          content_type=model.pk,
                                          object_id=object_id).first()
            if not et:
                entitytag = {
                    "tag": t.pk,
                    "content_type": model.pk,
                    "user": user.pk,
                    "object_id": object_id,
                }
                serializer = EntityTagSerializer(data=entitytag)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                response.append(serializer.instance)
        return Response(EntityTagSerializer(response, many=True).data,
                        status=HTTP_200_OK)
예제 #4
0
class ProductListSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, read_only=True, source='tag-set')
    prices = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()

    class Meta:
        model = Product
        fields = ('id', 'title', 'tags', 'prices', 'image')

    def get_prices(self, obj):
        prices = obj.unit_set.aggregate(max=Max('price'), min=Min('price'))
        return {'min': prices['min'], 'max': prices['max']}

    def get_image(self, obj):
        unit = obj.unit_set.filter(unitimage_isnull=False).first()
        if unit is None:
            return None

        image = unit.unitimage_set.order_by('-is_main').first()
        if image is None:
            return None

        return image.image.url


#class ProductSerializer(ProductListSerializer):
예제 #5
0
class NoteSerializer(serializers.ModelSerializer):
    """Serializer for notes"""

    tags = TagSerializer(many=True)

    class Meta:
        model = Note
        fields = '__all__'
        read_only_fields = ["user"]

    def create(self, validated_data):

        note = Note.objects.create(user=self.context['request'].user,
                                   title=validated_data.get('title'),
                                   body=validated_data.get(
                                       'body', validated_data.get('title')))

        for tag in validated_data.get('tags'):
            # check if tag exists or not
            _tag = Tag.objects.filter(
                name=tag['name'],
                created_by=self.context['request'].user).first()

            # if tag not exist, create one
            if not _tag:
                _tag = Tag.objects.create(
                    name=tag['name'], created_by=self.context['request'].user)

            # now attach it with the transaction
            note.tags.add(_tag)

        return note
예제 #6
0
def search_tags(request, repository, mucua, args):
    """
    busca tags a partir de uma string / fragmento    
    """
    logger.info(mucua)
    logger.info(args)

    # hack pra funcionar autocomplete
    # recebe também urls como /[repo]/[mucua]/tags/search/?q=[args]
    args_q = request.GET.get('q')
    if args_q != None:
        args = args_q
    
    # limpa url e pega argumentos
    args = args.split('/sort')[0]
    args = args.split('/limit')[0]
    args = args.split('/')
    
    for tag in args:
        tags = Tag.objects.all().filter(name__contains = tag)
    
    if args_q != None:
        response_data = []
        for t in tags:
            response_data.append(t.name) 
        return HttpResponse(json.dumps(response_data), mimetype=u'application/json')
    else:
        serializer = TagSerializer(tags, many=True)
        return Response(serializer.data)
예제 #7
0
 def post(self, request, *args, **kwargs):
     data = request.data
     queryset = Track.objects.filter(id=data.get("id"), Artist=request.user)
     if queryset.exists():
         if (data.get("Genre")):
             tag_serial = TagSerializer(data={"Genre": data.get("Genre")},
                                        partial=True)
             if (tag_serial.is_valid()):
                 tag_serial.save()
                 data["Tag"] = tag_serial.data["id"]
                 data.pop("Genre")
             else:
                 print('Invalid Genre error', track_serializer.errors)
                 return Response(track_serializer.errors,
                                 status=status.HTTP_400_BAD_REQUEST)
         track_serializer = TrackSerializer(queryset[0], data=data)
         if track_serializer.is_valid():
             track_serializer.save()
             return Response(track_serializer.data)
         else:
             print('error', track_serializer.errors)
             return Response(track_serializer.errors,
                             status=status.HTTP_400_BAD_REQUEST)
     else:
         print("Incorrect id, or invalid user")
         return Response({}, status=status.HTTP_400_BAD_REQUEST)
class VirtualServerSerializer(serializers.ModelSerializer):
    belong_business = BusinessSerializer(read_only=True, many=True)
    label = TagSerializer(read_only=True, many=True)
    asset_manager = StaffSerializer(read_only=True)

    class Meta:
        model = VirtualServer
        fields = '__all__'
예제 #9
0
class BlogSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, required=False)

    class Meta:
        model = Blog
        fields = [ "id", "title", "content",
            "date", "viewTimes", "owner",
            "series", "tags"]
예제 #10
0
class QuestionSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True, required=False)
    answers = AnswerSerializer(many=True, required=False)

    class Meta:
        model = Question
        fields = [
            "id", "title", "content", "date", "viewTimes", "owner", "status",
            "bounty", "tags", "answers"
        ]
예제 #11
0
class ProjectSerializer(serializers.ModelSerializer):

    client = AccountSerializer(Account)
    client_dashboard = DashboardSerializer(Dashboard)
    freelancer_dashboard = DashboardSerializer(Dashboard)
    tags = TagSerializer(many=True)
    compensation = CompensationSerializer(Compensation)

    class Meta:
        model = Project
        fields = '__all__'
class DeviceModelSerializer(serializers.ModelSerializer):
    belong_business = BusinessSerializer(read_only=True, many=True)
    label = TagSerializer(read_only=True, many=True)
    data_center = DatacenterSerializer(read_only=True)
    location_zone = RoomSerializer(read_only=True)
    location_cabinet = RackSerializer(read_only=True)
    series = SeriesSerializer(read_only=True)
    asset_manager = StaffSerializer(read_only=True)

    class Meta:
        model = DeviceModel
        fields = '__all__'
예제 #13
0
 def get(self, request, *args, **kwargs):
     preferenceset =UserPreferencesSerializer(request.user).data["preferences"]
     preferences = Preferences.objects.filter(preference_id__in=preferenceset)
     tagset = set()
     for preference in preferences:
         tagset = set(chain(tagset,PreferencesMappingSerializer(preference).data["tags"]))
     tags = Tag.objects.filter(tag_id__in=tagset)
     articleset = set()
     for tag in tags:
         articleset = set(chain(articleset,TagSerializer(tag).data["articles"]))
     articles = ArticleSerializer(Article.objects.filter(article_id__in= articleset),many=True).data
     return Response(articles, status=status.HTTP_200_OK)
예제 #14
0
def search_related_tags(request, repository, mucua, args):
    """
    a partir de um termo, buscar termos relacionados
    
    2 queries:
    - buscar medias que tem o termo e retornar lista de ids de media
    - puxar todas as tags das medias de lista de ids
    com quantidade de cada tag -> tag_count
    """
    
    # limpa url e pega argumentos
    args = args.split('/sort')[0]
    args = args.split('/limit')[0]
    args = args.split('/')

    try:
        this_mucua = Mucua.objects.get(description=mucua)
    except Mucua.DoesNotExist:
        this_mucua = Mucua.objects.get(description=DEFAULT_MUCUA)

    medias = Media.objects.all().filter(origin = this_mucua.id)

    # busca medias com termos buscados
    for s in args:
        medias = medias.filter(tags__name = s)

    medias_id = ''
    for media in medias:
        medias_id += str(media.id) + ','

    # compõe lista de ids de media
    medias_id = medias_id[:-1]

    # retorna tags da lista de ids gerada acima
    sql = "SELECT t.id, t.name, count(t.name) as tag_count \
    FROM \
    tag_tag t \
    LEFT JOIN \
    media_media_tags mt \
    ON mt.tag_id = t.id \
    LEFT JOIN  \
    media_media m \
    ON m.id = mt.media_id \
    WHERE \
    m.id IN (" + medias_id + ") \
    GROUP BY t.name"
    
    tags =  Tag.objects.raw(sql)
    
    serializer = TagSerializer(tags, many=True)
    return Response(serializer.data)
예제 #15
0
def mucua_tags(request, repository, mucua):

    """ 
    retorna todas as tags dos conteudos de origem [mucua]
    com quantidade de cada tag -> tag_count
    """
    
    if mucua == 'rede':
        tags = Tag.objects.all().filter(media__origin__isnull=False).annotate(tag_count=Count('name'))        
    else:
        try:
            this_mucua = Mucua.objects.get(description=mucua)
        except Mucua.DoesNotExist:
            this_mucua = Mucua.objects.get(description=DEFAULT_MUCUA)
        
        tags = Tag.objects.all().filter(media__origin = this_mucua.id).annotate(tag_count=Count('name'))
    
    serializer = TagSerializer(tags, many=True)
    return Response(serializer.data)   
예제 #16
0
    def retrieve(self, request, pk=None):
        if request.user.is_superuser:
            tag = Tag.objects.filter(tag_id=pk)
            articleset = set()
            for t in tag:
                articleset = set(
                    chain(articleset,
                          TagSerializer(t).data["articles"]))
            articles = ArticleSerializer(
                Article.objects.filter(article_id__in=articleset),
                many=True).data
            return Response(ArticleSerializer(articles, many=True).data)

        else:
            res = {
                'error':
                'can not authenticate with the given credentials or the account has been deactivated'
            }
            return Response(res, status=status.HTTP_403_FORBIDDEN)
예제 #17
0
 def post(self, request, *args, **kwargs):
     data = request.data
     data["Artist"] = request.user.id
     with connection.cursor() as cursor:
         cursor.execute(
             "SELECT id FROM album_album WHERE id = %s AND User_id = %s",
             [data["Album"], data["Artist"]])
         if (not cursor.fetchone()):
             return Response(
                 {
                     "error":
                     "Bad album id, or authenticated user does not own album"
                 },
                 status=status.HTTP_400_BAD_REQUEST)
     tag_serial = None
     if (data.get("Genre")):
         tag_serial = TagSerializer(data={"Genre": data.get("Genre")},
                                    partial=True)
         if (tag_serial.is_valid()):
             tag_serial.save()
             data["Tag"] = tag_serial.data["id"]
             data.pop("Genre")
         else:
             print('Invalid Genre error', track_serializer.errors)
             return Response(track_serializer.errors,
                             status=status.HTTP_400_BAD_REQUEST)
     track_serializer = TrackSerializer(data=request.data)
     if request.data["Album"] and track_serializer.is_valid():
         track_serializer.save()
         return Response(track_serializer.data,
                         status=status.HTTP_201_CREATED)
     else:
         if (tag_serial):
             tag_serial.delete()
         print('error', track_serializer.errors)
         return Response(track_serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
예제 #18
0
class EventSerializer(serializers.ModelSerializer):
    tags = TagSerializer(read_only=True, many=True)
    access_level = AccessLevelSerializer(read_only=True)
    event_types = EventTypeSerializer(read_only=True)
    publisher = UserSerializer(read_only=True)
    org = OrgSerializer(read_only=True)

    class Meta:
        model = Event
        fields = (
            'title',
            'slug',
            'event_date',
            'pub_date',
            'access_level',
            'location',
            'body',
            'event_types',
            'tags',
            'publisher',
            'org'
        )

        lookup_field = 'slug'
예제 #19
0
def get_top_tags_api(request):
    tags = get_top_tags()
    serializer = TagSerializer(instance=tags, many=True)
    return Response(serializer.data, status=200)
예제 #20
0
 def to_representation(self, value):
     return TagSerializer(value).data