Exemplo n.º 1
0
    def test_retrieve_tags(self):
        Tag.objects.bulk_create([
            Tag(user=self.user, name='Vegan'),
            Tag(user=self.user, name='Dessert'),
        ])

        res = self.client.get(TAGS_URL)

        tags = Tag.objects.all().order_by('-name')
        serializer = TagSerializer(tags, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)
Exemplo n.º 2
0
def addTag(name, objtype, objid):
    query = Tag.objects.filter(name=name, objtype=objtype, objid=objid)
    if query.count() == 0:
        tag = Tag(name=name, objtype=objtype, objid=objid)
        tag.save()
        return tag
    return None
Exemplo n.º 3
0
 def save(self):
     tag = Tag(wealth=self.wealth,
               name=self.cleaned_data['name'],
               modified_date=datetime.utcnow(),
               created_date=datetime.utcnow())
     tag.save()
     return tag
Exemplo n.º 4
0
def tag_edit(request, tag_id=None):
    msg = False
    if tag_id:
        tag = get_object_or_404(Tag, pk=tag_id)
        submit_url = reverse("core:tag_edit", kwargs={"tag_id": tag.id})
    else:
        tag = Tag()
        submit_url = reverse("core:tag_add")

    if request.method == "POST":
        form = forms.TagForm(request.POST, instance=tag)
        if form.is_valid():
            tag_new = form.save(commit=False)
            tag_new.owner = get_login_user(request.user.id)
            tag_new.save()
            return redirect("core:tag_index")

    form = forms.TagForm(instance=tag)
    return render(
        request,
        "dashboard/tag/edit.html",
        {
            "msg": msg,
            "form": form,
            "tag": tag,
            "submit_url": submit_url
        },
    )
Exemplo n.º 5
0
def add_tags_to_page(tag_text, page):
    tag_list = Tag.select().where(Tag.id << tag_text)

    tags_to_delete = TagAssociation.delete().where(
        TagAssociation.page == page, ~TagAssociation.tag << (tag_list))

    tags_to_delete.execute()

    tags_in_page = page.tags.select(Tag.id).tuples()

    tags_to_add = tag_list.select().where(~Tag.id << (tags_in_page))

    for n in tags_to_add:
        add_tag = TagAssociation(tag=n, page=page)

        add_tag.save()

    new_tags = json.loads(request.forms.getunicode('new_tags'))

    for n in new_tags:
        new_tag = Tag(tag=n, blog=page.blog)
        new_tag.save()

        add_tag = TagAssociation(tag=new_tag, page=page)

        add_tag.save()

    return tags_to_add, tags_to_delete, new_tags
Exemplo n.º 6
0
def tag_edit(request, tag_id=None):
    msg = False
    if tag_id:
        tag = get_object_or_404(Tag, pk=tag_id)
        submit_url = reverse("dashboard:tag_edit",
                             kwargs={'tag_id':tag.id})
    else:
        tag = Tag()
        submit_url = reverse("dashboard:tag_add")

    if request.method == 'POST':
        form = forms.TagForm(request.POST, instance=tag)
        if form.is_valid():
            tag_new = form.save(commit=False)
            tag_new.owner = get_login_user(request.user.id)
            tag_new.save()
            return redirect('dashboard:tag_index')

    form = forms.TagForm(instance=tag)
    return render(request,
                  'dashboard/tag/edit.html',
                  {'msg': msg,
                   'form': form,
                   'tag': tag,
                   'submit_url': submit_url})
Exemplo n.º 7
0
    def save_instance(self, instance):
        with transaction.atomic():
            instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
            super(VSGTenant, self).save_instance(instance)

            if instance.isolation in ["container", "container_vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network, ip="192.168.0.1", port_id="unmanaged")
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("device", "eth1")
                port.set_parameter("bridge", "br-lan")

                wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
                if not wan_networks:
                    raise XOSProgrammingError("No wan_network")
                port = self.find_or_make_port(instance, wan_networks[0])
                port.set_parameter("next_hop", value="10.0.1.253")   # FIX ME
                port.set_parameter("device", "eth0")

            if instance.isolation in ["vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network)
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("neutron_port_name", "stag-%s" % self.volt.s_tag)
                port.save()

            # tag the instance with the s-tag, so we can easily find the
            # instance later
            if self.volt and self.volt.s_tag:
                tags = Tag.objects.filter(name="s_tag", value=self.volt.s_tag)
                if not tags:
                    tag = Tag(service=self.provider_service, content_object=instance, name="s_tag", value=self.volt.s_tag)
                    tag.save()

            # VTN-CORD needs a WAN address for the VM, so that the VM can
            # be configured.
            if CORD_USE_VTN:
                tags = Tag.select_by_content_object(instance).filter(name="vm_vrouter_tenant")
                if not tags:
                    vrouter = self.get_vrouter_service().get_tenant(address_pool_name="addresses_vsg", subscriber_service = self.provider_service)
                    vrouter.set_attribute("tenant_for_instance_id", instance.id)
                    vrouter.save()
                    tag = Tag(service=self.provider_service, content_object=instance, name="vm_vrouter_tenant", value="%d" % vrouter.id)
                    tag.save()
Exemplo n.º 8
0
    def test_tag_str(self):
        user = sample_user()
        tag = Tag(
            user=user,
            name='Vegeterian',
        )

        self.assertEqual(str(tag), tag.name)
Exemplo n.º 9
0
    def test_url_is_unique(self):
        # Arrange.
        code = Tag.objects.get(name="Test 1").url

        # Act.
        tag = Tag(name="Test 2", url=code)

        # Assert.
        self.assertRaises(ValidationError, tag.save)
Exemplo n.º 10
0
    def test_get_existing_tag(self):
        """Tests that gets a tag instead of creating a new one"""
        name = 'comida'
        old_tag = Tag(name=name)
        old_tag.save()

        tag = Tag.objects.get_or_create_tag(name=name)

        self.assertEqual(tag.name, name)
        self.assertEqual(tag.id, old_tag.id)
Exemplo n.º 11
0
def add_tags_to_page(tag_text, page, no_delete=False):
    '''
    Takes a list of tags, in JSON text format, and adds them to the page in question.
    Any tags not already in the system will be added.

    :param tag_text:
        List of tags to add.
    :param page:
        Page object to add the tags to.
    :param no_delete:
        When set to True, this will preserve tags already in the page if they are
        not found in tag_text. By default this is False, so any tags not specified in
        tag_text that exist in the page will be removed.
    '''
    tag_list = Tag.select().where(Tag.id << tag_text)

    if no_delete is False:

        tags_to_delete = TagAssociation.delete().where(
            TagAssociation.page == page, ~TagAssociation.tag << (tag_list))

        tags_to_delete.execute()
    else:
        tags_to_delete = None

    tags_in_page = page.tags_all.select(Tag.id).tuples()

    tags_to_add = tag_list.select().where(~Tag.id << (tags_in_page))

    for n in tags_to_add:
        add_tag = TagAssociation(tag=n, page=page)

        add_tag.save()

    import json
    new_tags = json.loads(request.forms.getunicode('new_tags'))

    for n in new_tags:
        if n != '':
            new_tag = Tag(tag=n, blog=page.blog)
            new_tag.save()

            add_tag = TagAssociation(tag=new_tag, page=page)

            add_tag.save()

    return tags_to_add, tags_to_delete, new_tags
Exemplo n.º 12
0
def save_post():
    form = PostForm(request.form)
    if request.method == 'POST' and form.validate():
        blog = Routes.response_sql()
        title = form.title.data
        content = form.content.data
        p = Post(
            title=title,
            content=content,
            blog_id=blog.id_blog,
            create_date=datetime.datetime.now(),
            update_date=datetime.datetime.now(),
            status=1,
        )
        if 'tag' in request.form.keys() and request.form['tag'] != '':
            tag_post = request.form['tag'].split()
            tag_list = list()
            for tag in tag_post:
                tag_query = Tag.query.filter_by(name=tag_post)
                if tag_query.count() == 1:
                    id_tag = tag_query.first().id_tag
                else:
                    tag_model = Tag(
                        name=tag,
                        create_date=datetime.datetime.now(),
                        update_date=datetime.datetime.now(),
                        status=1,
                    )
                    tag_list += [tag_model]
            if len(tag_list) > 0:
                db.session.add_all(tag_list)
                db.session.commit()
                id_tag = db.session.query(Tag).order_by(
                    Tag.id_tag.desc()).first().id_tag

            p.tag_id = id_tag

        db.session.add(p)
        db.session.commit()
    return redirect(url_for('admin.default'))
Exemplo n.º 13
0
def get_test_tag():
    return Tag(name='comida')
Exemplo n.º 14
0
    def handle(self, *args, **options):
        if not Tag.objects.filter(name=STARRED_TAGNAME).exists():
            t = Tag(name=STARRED_TAGNAME)
            t.save()

        arg_album_name = options['album_name'][0] if options[
            'album_name'] else None

        if arg_album_name is not None:
            album_list = [arg_album_name]
        else:
            album_list = img_utils.get_album_list(settings.PHOTOS_BASEDIR)

        for album_name in album_list:
            _logger.debug("Generating db items for %s: ", album_name)
            try:
                album = Album.objects.get(name=album_name)
            except Album.DoesNotExist:
                album = Album(name=album_name)
                album.save()

            for photo in img_utils.get_photo_list(settings.PHOTOS_BASEDIR,
                                                  album_name):
                photo_relpath = img_utils.get_photo_filesystem_relpath(
                    album_name, photo)
                photo_abspath = img_utils.get_photo_filesystem_path(
                    settings.PHOTOS_BASEDIR, album_name, photo)
                photo_f = None
                try:
                    photo_f = open(photo_abspath, 'rb')
                    hashsum = img_utils.calc_mediafile_hash(photo_f)
                    photo_f.seek(0)
                    try:
                        mf = MediaFile.objects.get(file_hash=hashsum)
                        if mf.file_location != photo_relpath:
                            mf.file_location = photo_relpath
                            mf.save()
                    except MediaFile.DoesNotExist:
                        im = None
                        try:
                            im = Image.open(photo_f)
                            width, height = im.size
                            img_datetime = None
                            if hasattr(im, '_getexif'):
                                # noinspection PyProtectedMember
                                img_exif = im._getexif()
                                if img_exif:
                                    img_datetimedata = img_exif.get(
                                        EXIF_DATETIMEORIGINAL_TAG, None)
                                    try:
                                        img_datetime = img_utils.parse_exif_date(
                                            img_datetimedata
                                        ) if img_datetimedata else None
                                        if img_datetime:
                                            img_datetime = img_datetime.replace(
                                                tzinfo=pytz.UTC)
                                    except ValueError as v:
                                        _logger.warning(
                                            "Could not process date for %s, err: %s",
                                            photo_abspath, str(v))

                            mf = MediaFile(file_hash=hashsum,
                                           mediatype=models.MEDIATYPE_PHOTO,
                                           file_location=photo_relpath,
                                           width=width,
                                           height=height,
                                           date_taken=img_datetime)
                            try:
                                mf.save()
                            except django.db.utils.IntegrityError:
                                # Most probably file was modified, just update old record to preserve
                                # tags and comments
                                mf_old = MediaFile.objects.get(
                                    file_location=photo_relpath)
                                if MediaFile.objects.filter(
                                        file_location="DEL").exists():
                                    # This shouldn't exist but if we don't do this check a
                                    # uncleanly stopped previous job would break the makedb
                                    # command permanently
                                    MediaFile.objects.get(
                                        file_location="DEL").delete()
                                # Do this since file_location needs to be unique
                                mf_old.file_location = str("DEL")
                                mf_old.save()
                                mf.save()
                                mf_old.transfer_relations_to_other(mf)
                                mf_old.delete()

                        except OSError:
                            # this is not an image file, check for video
                            # TODO: work in progress
                            if os.path.splitext(photo_relpath)[-1] == ".MP4":
                                _logger.info("FOUND VIDEO")
                                mf = MediaFile(
                                    file_hash=hashsum,
                                    mediatype=models.MEDIATYPE_VIDEO,
                                    file_location=photo_relpath,
                                    width=0,
                                    height=0)
                                mf.save()
                            else:
                                raise IOError("")
                        finally:
                            if im is not None:
                                im.close()

                    try:
                        album_item = AlbumItem.objects.get(
                            file_location=photo_relpath)
                        album_item.media_file = mf
                        album_item.album = album
                    except AlbumItem.DoesNotExist:
                        album_item = AlbumItem(file_location=photo_relpath,
                                               album=album,
                                               media_file=mf)
                    album_item.save()

                except IOError:
                    _logger.warning("Could not process file: %s",
                                    photo_abspath)
                finally:
                    if photo_f is not None:
                        photo_f.close()
            album.gen_album_dates()
            album.save()

        if arg_album_name is None:
            # Delete albums where underlying folder is missing
            # Nothing should be linked to Album or AlbumItem so we should just be deleting
            # generated data
            for album in Album.objects.all():
                if album.name not in album_list:
                    print("Deleting album %s" % (album.name, ))
                    album.delete()

            all_files = set()
            for album_name in album_list:
                photo_dir = os.path.join(settings.PHOTOS_BASEDIR, album_name)
                all_files.update([
                    os.path.join(album_name, file_name)
                    for file_name in os.listdir(photo_dir)
                ])

            # Delete albums where underlying folder is missing. Note that comments, tags
            # and AlbumItems are linked to mediafiles and will be removed but since the
            # file does not exist anymore it should be ok
            for mf in MediaFile.objects.all():
                if mf.file_location not in all_files:
                    print("Removing file %s from database" %
                          (mf.file_location, ))
                    mf.delete()
Exemplo n.º 15
0
def create_fake_tags(number=10):
    Tag.objects.all().delete()
    for i in range(number):
        instance = Tag(name=fake.name())
        instance.save()
Exemplo n.º 16
0
 def save_tags(self, tags, post):
     for tag in tags:
         t = Tag(tag=tag)
         t.save()
         t.post.add(post)
Exemplo n.º 17
0
def profile_view(request, profile_id):

    profile = Profile.objects.get(pk=profile_id)
    now = datetime.datetime.now()

    if request.POST:
        comment = request.POST.get('comment')
        pro_tag = request.POST.get('pro-tag')
        con_tag = request.POST.get('con-tag')
        file = request.FILES.get('file')
        star_rating = request.POST.get('stars')
        if comment:
            title = request.POST.get('comment-title')
            review = Review(title=title, comment=comment, date=now)
            review.save()
            profile.reviews.add(review)
        elif pro_tag:
            try:
                tag = Tag.objects.get(title=pro_tag, isPro=1)
            except ObjectDoesNotExist:
                tag = Tag(title=pro_tag, isPro=1)
                tag.save()

            user_tag = UserTag(tag=tag)
            user_tag.save()
            profile.pro_tags.add(user_tag)
        elif con_tag:
            try:
                tag = Tag.objects.get(title=pro_tag, isPro=0)
            except ObjectDoesNotExist:
                tag = Tag(title=con_tag, isPro=0)
                tag.save()

            user_tag = UserTag(tag=tag)
            user_tag.save()
            profile.con_tags.add(user_tag)
        elif file:
            photo_form = PhotoForm(request.POST, request.FILES)
            if photo_form.is_valid():
                image = photo_form.save()
                profile.images.add(image)
        elif star_rating:
            rating = StarRating(value=star_rating, date=now)
            rating.save()
            profile.star_ratings.add(rating)

    # profile_id = request.POST.get('profile_id')

    total = 0
    count = 0
    for rating in profile.star_ratings.all():
        count += 1
        total += rating.value

    overall_rating = round(total / count, 0) if count else 0

    history = getHistory(profile)
    photo_form = PhotoForm()

    context = {
        'profile': profile,
        'rating': overall_rating,
        'history': history,
        'photo_form': photo_form
    }

    return render(request, 'core/profile.html', context)