Exemple #1
0
def submit(request):
    if request.method == "POST":
        form = SubmissionForm(request.POST)
        if form.is_valid():
            caption = form.cleaned_data['caption']
            url = form.cleaned_data['image_url']
            categories = [category.pk for category in Category.objects.all()]
            
            im = Image(caption=caption, 
                       url=url,
                       user=request.user)
            try:
                im.save() # need to save before adding many to many relationships
            except IntegrityError:
                # assume url column not unique..image already added
                im = Image.objects.get(url=url)
                return redirect('/im/%d' % im.pk)
            im.apply_categories(categories)
            
            messages.success(request, 'Image submitted successfully!')
            return redirect('/submit')
    else:
        form = SubmissionForm()
    
    return render_to_response("submit.html", {
            'form': form,
        },
        context_instance = RequestContext(request)
    )
Exemple #2
0
    def create(self):
        xos_args = self.get_xos_args()

        image = Image(**xos_args)
        image.caller = self.user
        image.save()

        self.info("Created Image '%s'" % (str(image), ))
Exemple #3
0
    def create(self):
        xos_args = self.get_xos_args()

        image = Image(**xos_args)
        image.caller = self.user
        image.save()

        self.info("Created Image '%s'" % (str(image), ))
Exemple #4
0
 def _create_image(self, gallery, instance):
     '''
         Создает core.models.Image
         с привязкой к нужному объекту
     '''
     from core.models import Image
     image = Image(img=instance, gallery=gallery)
     image.save()
     return image
Exemple #5
0
 def _download_image_and_update_fields(self, image: Image) -> None:
     img_bytes, _, status_code = asyncio.run(self.connector.get_page(RequestBody(image.marketplace_link, 'get',
                                                                                 parsing_type='image')))
     if status_code == 200:
         image.image_file.save(image.marketplace_link.split('/')[-1], ContentFile(img_bytes), save=False)
     else:
         logger.error(f'Can not find image on link {image.marketplace_link}')
     image.next_parse_time = now() + self.config.images_parse_frequency
     image.start_parse_time = None
     image.save()
Exemple #6
0
def run(rootpath):

    print(f'Start indexing from {rootpath}...')

    files = []

    # with open('output.txt', 'w') as f:
    #     for dirpath, dirnames, filenames in os.walk('.'):
    #         for fullpath in [os.path.join(dirpath, filename) for filename in filenames]:
    #             f.write(f'{fullpath}\n')

    for dirpath, dirnames, filenames in os.walk(rootpath):
        for filename in filenames:
            fullpath = os.path.join(dirpath, filename)
            if 'image' not in mimetypes.guess_type(fullpath)[0]:
                continue

            file = File(fullpath)
            file.image_date = try_parse_image_date_from_file(fullpath)

            files.append(file)
        break

    files.sort(key=lambda file: (file.image_date is None, file.image_date))

    for file in files:
        print(file.image_date, file.fullpath)

    for file in files:
        src = file.fullpath
        id = uuid.uuid4()
        _, file_extension = os.path.splitext(fullpath)
        new_filename = f'{id}{file_extension}'
        dst = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT,
                           new_filename)

        print(f'Copying from {src} to {dst}')
        shutil.copyfile(src, dst)

        file.new_fullpath = dst
        file.id = id

    album = Album.objects.get(name='image_indexer')

    for file in files:
        image = Image(
            id=file.id,
            album=album,
            original=os.path.basename(file.new_fullpath),
            image_date=make_aware(file.image_date),
            source=os.path.relpath(file.fullpath, rootpath),
            sha256_checksum=get_file_sha256(file.new_fullpath),
        )
        image.save()
def add_feedback(request, product_id):
    if request.method == 'POST':
        feedback = Feedback(user=request.user,
                            text=request.POST.get("text"),
                            rate=int(request.POST.get("rate")),
                            datetime=datetime.now(),
                            product=BaseProduct.objects.get(id=product_id))
        feedback.save()
        if request.FILES:
            for photo in request.FILES.getlist("photos"):
                image = Image(image=photo)
                image.save()
                feedback.images.add(image)
            feedback.save()

    return HttpResponseRedirect(f"/product/{product_id}")
Exemple #8
0
def create_image(miracle, type, url, title, year=None):
    try:
        new_image = Image()
        new_image.miracle = miracle
        new_image.type = type
        new_image.url = url
        new_image.title = title
        if year is not None:
            new_image.year = year
        new_image.save()
    except:  #not unique or contains invalid characters
        pass
    return
Exemple #9
0
 def clean_image_url(self):
     """
     Check that the image url is valid.
     See: http://stackoverflow.com/questions/2486145/python-check-if-url-to-jpg-exists
     """
     if not Image.check_image_url(self.cleaned_data['image_url']):
         raise forms.ValidationError("Please enter a valid image URL!")
     
     return self.cleaned_data['image_url']
Exemple #10
0
    def get(self, request, *args, **kwargs):
        is_classification = request.GET.get('is_classification') == 'true'
        classes = ImageClass.classes_for_classification() if is_classification else ImageClass.objects.all()
        image = Image.get_random_image()

        return Response({
            'image': ImageSerializer(image).data,
            'classes': ImageClassSerializer(classes, many=True).data
        })
Exemple #11
0
    def clean_image_url(self):
        """
        Check that the image url is valid.
        See: http://stackoverflow.com/questions/2486145/python-check-if-url-to-jpg-exists
        """
        if not Image.check_image_url(self.cleaned_data['image_url']):
            raise forms.ValidationError("Please enter a valid image URL!")

        return self.cleaned_data['image_url']
Exemple #12
0
    def add_auction(cls, request):
        if request.method == "POST":
            form = AuctionForm(request.POST, request.FILES)
            if form.is_valid():
                base_item = BaseItem()
                base_item.name = form.cleaned_data["name"]
                base_item.save()
                base_item.categories = form.cleaned_data["categories"]
                base_item.description = form.cleaned_data["description"]
                base_item.thumb = form.cleaned_data["thumb"]
                base_item.is_active = True

                image = Image()
                image.image = form.cleaned_data["image"]
                image.save()

                base_item.images.add(Image.objects.get(pk=image.pk))
                base_item.save()

                auction = AuctionItem()
                auction.base = base_item
                auction.start_date = form.cleaned_data["start_date"]
                auction.planned_close_date = form.cleaned_data[
                    "planned_close_date"]
                auction.start_price = form.cleaned_data["start_price"]
                auction.current_price = auction.start_price
                auction.reserve_price = form.cleaned_data["reserve_price"]
                auction.properties = "{}"

                current_user = ShopUser.objects.get(user__pk=request.user.pk)
                auction.created_by = current_user

                auction.save()

                return HttpResponseRedirect("/aukcje/%s/" % str(auction.pk))
            else:
                return render_to_response(
                    "auction_add.html", {'form': form},
                    context_instance=RequestContext(request))
        else:
            form = AuctionForm()
            return render_to_response("auction_add.html", {'form': form},
                                      context_instance=RequestContext(request))
Exemple #13
0
    def add_auction(cls, request):
        if request.method == "POST":
            form = AuctionForm(request.POST, request.FILES)
            if form.is_valid():
                base_item = BaseItem()
                base_item.name = form.cleaned_data["name"]
                base_item.save()
                base_item.categories = form.cleaned_data["categories"]
                base_item.description = form.cleaned_data["description"]
                base_item.thumb = form.cleaned_data["thumb"]
                base_item.is_active = True

                image = Image()
                image.image = form.cleaned_data["image"]
                image.save()

                base_item.images.add(Image.objects.get(pk=image.pk))
                base_item.save()

                auction = AuctionItem()
                auction.base = base_item
                auction.start_date = form.cleaned_data["start_date"]
                auction.planned_close_date = form.cleaned_data[
                    "planned_close_date"]
                auction.start_price = form.cleaned_data["start_price"]
                auction.current_price = auction.start_price
                auction.reserve_price = form.cleaned_data["reserve_price"]
                auction.properties = "{}"

                current_user = ShopUser.objects.get(user__pk=request.user.pk)
                auction.created_by = current_user

                auction.save()

                return HttpResponseRedirect("/aukcje/%s/" % str(auction.pk))
            else:
                return render_to_response("auction_add.html", {'form': form},
                                          context_instance=RequestContext(request))
        else:
            form = AuctionForm()
            return render_to_response("auction_add.html", {'form': form},
                                      context_instance=RequestContext(request))
Exemple #14
0
    def post(self, request, *args, **kwargs):
        image = Image.objects.get(pk=request.data['image_id'])
        image.delete()

        is_classification = request.data.get('is_classification')
        classes = ImageClass.classes_for_classification() if is_classification else ImageClass.objects.all()

        return Response({
            'image': ImageSerializer(Image.get_random_image()).data,
            'classes': ImageClassSerializer(classes, many=True).data
        })
Exemple #15
0
def create_image(miracle, type, url, title, year = None):
    try:
        new_image = Image()
        new_image.miracle = miracle
        new_image.type = type
        new_image.url = url
        new_image.title = title
        if year is not None:
            new_image.year = year
        new_image.save()
    except : #not unique or contains invalid characters
        pass
    return
Exemple #16
0
def submit(request):
    if request.method == "POST":
        form = SubmissionForm(request.POST)
        if form.is_valid():
            caption = form.cleaned_data['caption']
            url = form.cleaned_data['image_url']
            categories = [category.pk for category in Category.objects.all()]

            im = Image(caption=caption, url=url, user=request.user)
            try:
                im.save(
                )  # need to save before adding many to many relationships
            except IntegrityError:
                # assume url column not unique..image already added
                im = Image.objects.get(url=url)
                return redirect('/im/%d' % im.pk)
            im.apply_categories(categories)

            messages.success(request, 'Image submitted successfully!')
            return redirect('/submit')
    else:
        form = SubmissionForm()

    return render_to_response("submit.html", {
        'form': form,
    },
                              context_instance=RequestContext(request))
    def handle(self, *args, **options):
        print('\nSTART\n\n')

        image_folder = options.get('image_folder')

        if not image_folder:
            print(
                'Укажите путь к папке с загружаемыми изображениями!\n'
                '(например: python manage.py upload_images --image-folder="/home/user/image_folder")'
            )
            return

        images = []

        for image in os.listdir(image_folder):
            full_path = os.path.join(image_folder, image)
            images.append(full_path)

        for path_to_image in images:
            Image.create_from_path(path_to_image)

        print('\n\nFINISH\n')
Exemple #18
0
 def form_valid(self, form):
     image = Image()
     image.user = self.request.user
     image.image_obj = self.request.FILES.get('image_obj')
     if form.fields['description']:
         image.description = form.fields['description']
     # if form.fields['hashtag']:
     #     hashtag = HashTag
     image.save()
     # Todo: add hashtag
     return HttpResponseRedirect(self.success_url)
Exemple #19
0
def scrapers():
    to_add = []
    print "GOT HERE"
    to_add.extend(reddit_pics())
    to_add.extend(parse_from_src("http://www.someecards.com/combined-rss", 'someecards'))
    to_add.extend(parse_from_src("http://feeds.feedburner.com/ImgurGallery?format=rss", 'imgur'))
    
    random.shuffle(to_add, random.random)
    
    for im in to_add:
        cat_ids = get_categories()
        im = Image.create_image(url=im[0], caption=im[1], source=im[2])
        if im:
            im.apply_categories(cat_ids)
Exemple #20
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newimage = Image(imagefile=request.FILES['docfile'],
                             user=request.user,
                             status=request.POST['select'])
            newimage.save()

            # Redirect to the images list after POST
            return HttpResponseRedirect('/list')
    else:
        form = DocumentForm()  # A empty, unbound form

    # Load documents for the list page
    images = Image.objects.filter(user=request.user)

    # Render list page with the images and the form
    return render_to_response('list.html', {
        'images': images,
        'form': form
    },
                              context_instance=RequestContext(request))
Exemple #21
0
def scrapers():
    to_add = []
    print "GOT HERE"
    to_add.extend(reddit_pics())
    to_add.extend(
        parse_from_src("http://www.someecards.com/combined-rss", 'someecards'))
    to_add.extend(
        parse_from_src("http://feeds.feedburner.com/ImgurGallery?format=rss",
                       'imgur'))

    random.shuffle(to_add, random.random)

    for im in to_add:
        cat_ids = get_categories()
        im = Image.create_image(url=im[0], caption=im[1], source=im[2])
        if im:
            im.apply_categories(cat_ids)
Exemple #22
0
    def post(self, request, *args, **kwargs):
        image_id = request.data['image_id']
        detections = self.__prepare_data(request.data, image_id)
        user = request.user
        if user.pk is None:
            user, _ = get_user_model().objects.get_or_create(username='******')

        with transaction.atomic():
            for detection in detections:
                # поправить, что это тоже передавалось в serializer
                image_class = detection.pop('image_class', None)
                serializer = self.get_serializer(data=detection)
                serializer.is_valid(raise_exception=True)
                serializer.save(image_class_id=image_class, image_id=image_id, user=user)

        return Response({
            'image': ImageSerializer(Image.get_random_image()).data,
            'classes': ImageClassSerializer(ImageClass.objects.all(), many=True).data
        })
Exemple #23
0
    def post(self, request, *args, **kwargs):
        data = request.data

        user = request.user
        if user.pk is None:
            user, _ = get_user_model().objects.get_or_create(username='******')
       
        Classification.objects.create(
            user=user,
            image_id=data.get('image_for_classification'),
            technique_id=data.get('technique'),
            image_class_id=data.get('image_class'),
            style_id=data.get('style')
        )

        image = Image.get_random_image()

        return Response({
            'image': ImageSerializer(image).data,
            'classes': ImageClassSerializer(ImageClass.classes_for_classification(), many=True).data
        })
Exemple #24
0
    def __init__(self, request, *args, **kwargs):
        super(SystemObject, self).__init__(request, *args, **kwargs)
        self.manager = AdminManager()
        self.manager.fetchOptions = {
            'site': int(self.portal.activeSite.id),
            'active': self.requester.rData['selectedactivity'],
            'activesite': self.requester.rData['activesite']
        }
        self.urls.add = 'core.view.imageadmin.add_item'
        self.urls.edit = 'core.view.imageadmin.edit_item'
        self.urls.show_items = 'core.view.imageadmin.show_items'
        self.manager.model = Image()
        self.manager.modelLanguage = ImageLanguage()
        self.manager.form_class = AdmItemForm().__class__
        self.manager.language_form_class = AdmItemLanguageForm().__class__
        self.manager.order = 'date'
        self.manager.debugger.filename = 'imageadmin.py'
        self.manager.moduleName = '__adm_Articles__'
        self.data.update(
            {'filter_activity': reverse('core.view.imageadmin.show_items')})
        self.data.update({
            'savebutton': 1,
            'saveaddbutton': 1,
            'copybutton': 1,
            'addbutton': 1
        })

        self.gallery = AdminManager()
        self.gallery.model = Gallery()
        self.gallery.order = 'parent'
        self.gallery.fetchOptions = {
            'site': self.portal.activeSite.id,
            'active': self.requester.rData['selectedactivity'],
            'activesite': self.requester.rData['activesite']
        }
        self.gallery.modelLanguage = GalleryLanguage()
Exemple #25
0
 def _extract_info_from_page(
     self, all_items: List[Tag]
 ) -> Tuple[List[int], Dict[int, Image], Dict[str, int]]:
     marketplace_ids, imgs, link_to_ids = [], {}, {}
     for item in all_items:
         found_image = False
         for tag in item.findAll('img'):
             link = tag.get('src')
             if link is not None and 'blank' not in link:
                 img_link = 'https:' + link
                 img_obj = Image(marketplace_link=img_link,
                                 marketplace_source=self.marketplace_source,
                                 next_parse_time=now())
                 imgs[int(item['data-popup-nm-id'])] = img_obj
                 link_to_ids[img_link] = int(item['data-popup-nm-id'])
                 marketplace_ids.append(int(item['data-popup-nm-id']))
                 found_image = True
                 break
         if not found_image:
             logger.error(
                 f'Found item with no image. Check it:\n\n{item.prettify()}'
             )
             marketplace_ids.append(int(item['data-popup-nm-id']))
     return marketplace_ids, imgs, link_to_ids
    def handle_form_save(self, request, upload_form):
        """Save the data into database"""

        if upload_form.is_valid():
            try:
                PhotoObj = Photographer.objects.get(user_ref=request.user)
                if len(PhotoObj.image.all()):
                    for k in PhotoObj.image.all():
                        k.delete_image(os.path.join(MEDIA_ROOT, k.image.name))
                        k.delete()
                PhotoObj.home_page_desc = upload_form.cleaned_data['home_page_desc']
                # PhotoObj.image_1_desc = upload_form.cleaned_data['image_1_desc']
                # PhotoObj.image_2_desc = upload_form.cleaned_data['image_2_desc']
                # PhotoObj.image_3_desc = upload_form.cleaned_data['image_3_desc']
                PhotoObj.save()

                # image = Image(content_object=PhotoObj, image_name=upload_form.cleaned_data['image_1_name'])

                try:
                    image = Image(content_object=PhotoObj)
                    (image.image,image_name) = Image().copy_upload_image(PhotoObj, upload_form.cleaned_data['image_1_name'], request.user.username)
                    image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award1
                    image.image_a_name = image_name
                    image.image_desc = upload_form.cleaned_data['image_1_desc']
                    image.save()
                except Exception as e:
                    print str(e)
                    print "\n Inside Exception"
                    Image.objects.create(content_object=PhotoObj, image_name=IMAGE_NAME_CHOICES['TYPE'].Award1,
                         image_a_name=image_name, image_desc=upload_form.cleaned_data['image_1_desc']
                    )


                generate_version_add_watermark(image.image.name, 'thumbnail')

                image = Image(content_object=PhotoObj)
                (image.image,image_name) = Image().copy_upload_image(PhotoObj, upload_form.cleaned_data['image_2_name'], request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award2
                image.image_a_name = image_name
                image.image_desc = upload_form.cleaned_data['image_2_desc']
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')

                image = Image(content_object=PhotoObj)
                (image.image,image_name) = Image().copy_upload_image(PhotoObj, upload_form.cleaned_data['image_3_name'], request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award3
                image.image_a_name = image_name
                image.image_desc = upload_form.cleaned_data['image_3_desc']
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')


                image = Image(content_object=PhotoObj)
                (image.image,image_name) = Image().copy_upload_image(PhotoObj, upload_form.cleaned_data['profile_image_name'], request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Profileimage
                image.image_a_name = image_name
                image.profile_image = True
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')

                return redirect("photographerprofile")

            except Exception as ex:
                raise Exception(str(ex))
        else:
            try:
                pass
                # if len(upload_form.cleaned_data['image_1_name']):
                #     dt = upload_form.cleaned_data['image_1_name']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_1_name'] = fn[0].split('/media/_versions/temp/')[1] + ln


                # if len(upload_form.cleaned_data['image_2']):
                #     dt = upload_form.cleaned_data['image_2']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_2_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_3']):
                #     dt = upload_form.cleaned_data['image_3']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_3_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_4']):
                #     dt = upload_form.cleaned_data['image_4']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_4_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_5']):
                #     dt = upload_form.cleaned_data['image_5']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_5_name'] = fn[0].split('/media/_versions/temp/')[1] + ln

            except Exception as e:
                pass

            return Response({'upload_form': upload_form, 'username': request.user.username}, template_name='uploads.html')
Exemple #27
0
    def auction_edit(cls, request, id):
        auction = AuctionItem.objects.get(pk=id)
        base = auction.base
        if request.method == "POST":
            form = EditAuctionForm(request.POST, request.FILES)
            if form.is_valid():
                base.name = form.cleaned_data["name"]
                base.categories = form.cleaned_data["categories"]
                base.description = form.cleaned_data["description"]
                base.thumb = form.cleaned_data["thumb"]

                image = Image()
                image.image = form.cleaned_data["image"]
                image.save()

                base.images.clear()
                base.images.add(Image.objects.get(pk=image.pk))

                props = {}
                for line in form.cleaned_data["properties"].split("\n"):
                    line = line.split(":")
                    if len(line) == 2:
                        key, value = line
                        props[key] = value
                    else:
                        continue

                props = json.dumps(props, sort_keys=True)
                base.properties = props
                base.save()

                auction.base = base
                auction.start_date = form.cleaned_data["start_date"]
                auction.planned_close_date = form.cleaned_data[
                    "planned_close_date"]
                auction.reserve_price = form.cleaned_data["reserve_price"]

                auction.save()

                return HttpResponseRedirect("/aukcje/%s/" % str(auction.pk))
            else:
                return render_to_response(
                    "auction_edit.html",
                    {"form": form},
                    context_instance=RequestContext(request))
        else:
            fields = {}
            for cat in base.categories.all():
                try:
                    fields.update(json.loads(cat.properties))
                except Exception:
                    pass
            props = "\n".join([str(key) + ": \n" for key in fields.keys()])
            form = EditAuctionForm(
                initial={
                    "name": base.name,
                    "categories": base.categories.all(),
                    "properties": props,
                    "thumb": base.thumb,
                    "image": base.images.all()[0],
                    "start_date": auction.start_date,
                    "planned_close_date": auction.planned_close_date,
                    "reserve_price": auction.reserve_price})
            return render_to_response("auction_edit.html", {"form": form},
                                      context_instance=RequestContext(request))
Exemple #28
0
    def add_item(cls, request):
        if request.method == 'POST':
            form = EshopItemForm(request.POST)
            if form.is_valid():
                #nowy BaseItem
                base_name = request.POST['name']
                base_category_name = request.POST['category']
                base_category = Category.objects.get(pk=base_category_name)
                #properties konstrukcja Json
                json = '{'
                properties = [
                    [request.POST['properties1'], request.POST['pname1']],
                    [request.POST['properties2'], request.POST['pname2']],
                    [request.POST['properties3'], request.POST['pname3']],
                    [request.POST['properties4'], request.POST['pname4']],
                    [request.POST['properties5'], request.POST['pname5']],
                    [request.POST['properties6'], request.POST['pname6']]
                ]
                i = 0
                for property in properties:
                    if property[0]:
                        if i < len(properties) and i > 0:
                            json = json + ',\r\n'
                        i = i + 1
                        json = json + '"' + property[1] + '":"' + property[
                            0] + '"'

                json = json + '}'

                #
                base_description = request.POST['description']
                base_thumb = request.FILES.get('thumb')
                base_is_active = request.POST['is_active']
                #
                new_base = BaseItem(name=base_name,
                                    properties=json,
                                    description=base_description,
                                    thumb=base_thumb,
                                    is_active=base_is_active)
                new_base.save()

                #images
                image1 = request.FILES.get('image1')
                new_image1 = Image(image=image1)
                if image1:
                    new_image1.save()
                    new_base.images.add(new_image1)
                image2 = request.FILES.get('image2')
                new_image2 = Image(image=image2)
                if image2:
                    new_image2.save()
                    new_base.images.add(new_image2)
                image3 = request.FILES.get('image3')
                new_image3 = Image(image=image3)
                if image3:
                    new_image3.save()
                    new_base.images.add(new_image3)

                #dodaj kategorie i obrazy
                new_base.categories.add(base_category)
                new_base.save()
                #nowy EshopItem
                price = request.POST['price']
                is_on_sale = request.POST.get('is_on_sale', False)
                discount_price = request.POST.get('discount_price')
                availiability_status_name = request.POST[
                    'availiability_status']
                availiability_status = AvailiabilityStatus.objects.get(
                    pk=availiability_status_name)
                current_stock = request.POST['current_stock']

                new_eshopitem = EShopItem(
                    price=price,
                    is_on_sale=is_on_sale,
                    discount_price=discount_price,
                    availiability_status=availiability_status,
                    current_stock=current_stock,
                    base=new_base)
                new_eshopitem.save()
                return HttpResponseRedirect("/manager/sklep/")
        else:
            form = EshopItemForm(initial={"discount_price": 0})
        return render_to_response('backpanel_new_item.html', {'form': form},
                                  context_instance=RequestContext(request))
Exemple #29
0
    def auction_edit(cls, request, id):
        auction = AuctionItem.objects.get(pk=id)
        base = auction.base
        if request.method == "POST":
            form = EditAuctionForm(request.POST, request.FILES)
            if form.is_valid():
                base.name = form.cleaned_data["name"]
                base.categories = form.cleaned_data["categories"]
                base.description = form.cleaned_data["description"]
                base.thumb = form.cleaned_data["thumb"]

                image = Image()
                image.image = form.cleaned_data["image"]
                image.save()

                base.images.clear()
                base.images.add(Image.objects.get(pk=image.pk))

                props = {}
                for line in form.cleaned_data["properties"].split("\n"):
                    line = line.split(":")
                    if len(line) == 2:
                        key, value = line
                        props[key] = value
                    else:
                        continue

                props = json.dumps(props, sort_keys=True)
                base.properties = props
                base.save()

                auction.base = base
                auction.start_date = form.cleaned_data["start_date"]
                auction.planned_close_date = form.cleaned_data[
                    "planned_close_date"]
                auction.reserve_price = form.cleaned_data["reserve_price"]

                auction.save()

                return HttpResponseRedirect("/aukcje/%s/" % str(auction.pk))
            else:
                return render_to_response(
                    "auction_edit.html", {"form": form},
                    context_instance=RequestContext(request))
        else:
            fields = {}
            for cat in base.categories.all():
                try:
                    fields.update(json.loads(cat.properties))
                except Exception:
                    pass
            props = "\n".join([str(key) + ": \n" for key in fields.keys()])
            form = EditAuctionForm(
                initial={
                    "name": base.name,
                    "categories": base.categories.all(),
                    "properties": props,
                    "thumb": base.thumb,
                    "image": base.images.all()[0],
                    "start_date": auction.start_date,
                    "planned_close_date": auction.planned_close_date,
                    "reserve_price": auction.reserve_price
                })
            return render_to_response("auction_edit.html", {"form": form},
                                      context_instance=RequestContext(request))
Exemple #30
0
    def post(self, request, format=None):
        new_doc = DocumentSerializer(data=request.data)
        if new_doc.is_valid():
            new_doc.save()
            dataset = Dataset(document=Document.objects.latest('id'))
            dataset.dataType = request.data['dataType']
            dataset.save()
            if request.data['dataType'] == 'Image Labeling':
                docName = os.path.join(
                    settings.MEDIA_ROOT,
                    Document.objects.latest('id').doc_file.name)
                extractPath = os.path.join(settings.MEDIA_ROOT,
                                           str(dataset.id))
                zip_ref = zipfile.ZipFile(docName, 'r')
                zip_ref.extractall(extractPath)
                zip_ref.close()
                print('extract successfull')
                dirs = os.listdir(path=extractPath)
                print(dirs)
                for dir in ['images', 'questions.csv'
                            ]:  # questions.csv must be checked at "last"
                    if not os.path.exists(os.path.join(extractPath, dir)):
                        # bad file structure
                        break
                    if dir == 'questions.csv':
                        chopToMicrotasks(os.path.join(extractPath, dir), Image,
                                         ImageLabelingTask, 'images')
                        continue
                    # dir == "images"
                    imagesDir = os.path.join(extractPath, dir)
                    for r, d, f in os.walk(top=imagesDir):
                        for file in f:
                            img = Image(name=file)
                            img.contentPath = os.path.join(imagesDir, file)
                            img.save()

            elif request.data['dataType'] == 'Voice To Text':
                docName = os.path.join(
                    settings.MEDIA_ROOT,
                    Document.objects.latest('id').doc_file.name)
                extractPath = os.path.join(settings.MEDIA_ROOT,
                                           str(dataset.id))
                zip_ref = zipfile.ZipFile(docName, 'r')
                zip_ref.extractall(extractPath)
                zip_ref.close()
                print('extract successfull')
                dirs = os.listdir(path=extractPath)
                print(dirs)
                for dir in ['voices', 'questions.csv'
                            ]:  # questions.csv must be checked at "last"
                    if not os.path.exists(os.path.join(extractPath, dir)):
                        # bad file structure
                        break
                    if dir == 'questions.csv':
                        chopToMicrotasks(os.path.join(extractPath, dir), Voice,
                                         VoiceToTextTask, 'voices')
                        continue
                    # dir == "voices"
                    voicesDir = os.path.join(extractPath, dir)
                    for r, d, f in os.walk(top=voicesDir):
                        for file in f:
                            vc = Voice(name=file)
                            vc.contentPath = os.path.join(voicesDir, file)
                            vc.save()

            elif request.data['dataType'] == 'Text To Voice':
                docName = os.path.join(
                    settings.MEDIA_ROOT,
                    Document.objects.latest('id').doc_file.name)
                extractPath = os.path.join(settings.MEDIA_ROOT,
                                           str(dataset.id))
                zip_ref = zipfile.ZipFile(docName, 'r')
                zip_ref.extractall(extractPath)
                zip_ref.close()
                print('extract successfull')
                dirs = os.listdir(path=extractPath)
                print(dirs)
                for dir in ['texts', 'questions.csv'
                            ]:  # questions.csv must be checked at "last"
                    if not os.path.exists(os.path.join(extractPath, dir)):
                        # bad file structure
                        break
                    if dir == 'questions.csv':
                        chopToMicrotasks(os.path.join(extractPath, dir), Image,
                                         ImageLabelingTask, 'images')
                        continue
                    # dir == "images"
                    imagesDir = os.path.join(extractPath, dir)
                    for r, d, f in os.walk(top=imagesDir):
                        for file in f:
                            img = Image(name=file)
                            img.contentPath = os.path.join(imagesDir, file)
                            img.save()

            elif request.data['dataType'] == 'Text To Text':
                docName = os.path.join(
                    settings.MEDIA_ROOT,
                    Document.objects.latest('id').doc_file.name)
                extractPath = os.path.join(settings.MEDIA_ROOT,
                                           str(dataset.id))
                zip_ref = zipfile.ZipFile(docName, 'r')
                zip_ref.extractall(extractPath)
                zip_ref.close()
                print('extract successfull')
                dirs = os.listdir(path=extractPath)
                print(dirs)
                for dir in ['texts', 'questions.csv'
                            ]:  # questions.csv must be checked at "last"
                    if not os.path.exists(os.path.join(extractPath, dir)):
                        # bad file structure
                        break
                    if dir == 'questions.csv':
                        chopToMicrotasks(os.path.join(extractPath, dir), Text,
                                         TextToTextTask, 'texts')
                        continue
                    # dir == "texts"
                    textsDir = os.path.join(extractPath, dir)
                    for r, d, f in os.walk(top=textsDir):
                        for file in f:
                            txt = Text(name=file)
                            txt.contentPath = os.path.join(textsDir, file)
                            txt.save()

            return Response(status=204)

        return Response(new_doc.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #31
0
        section.save()

if ask_reimport("pictures"):
    Image.objects.all().delete()

    reimport_files = ask_reimport("image files")

    for old_pic in read_table("picture"):
        try:
            pic_id = get_field(old_pic, "id")
            date = read_date(get_field(old_pic, "date"))
            pic = Image(
                legacy_id=get_field(old_pic, "id"),
                title=get_field(old_pic, "title", ""),
                description=get_field(old_pic, "caption", ""),
                created=date,
                modified=date,
                guest_authors=get_field(old_pic, "altAuthor", ""),
                visibility=Content.PUBLISHED,
            )

            extension = {
                "image/jpeg": "jpg",
                "image/png": "png",
                "image/gif": "gif"
            }[get_field(old_pic, "mimeType")]
            file_name = "{}.{}".format(pic_id, extension)

            if reimport_files:
                file = File(
                    open("import/data/images/{}".format(file_name), "rb"))
Exemple #32
0
                          title=get_field(old_category, "name"))
        section.save()

if ask_reimport("pictures"):
    Image.objects.all().delete()

    reimport_files = ask_reimport("image files")

    for old_pic in read_table("picture"):
        try:
            pic_id = get_field(old_pic, "id")
            date = read_date(get_field(old_pic, "date"))
            pic = Image(legacy_id=get_field(old_pic, "id"),
                        title=get_field(old_pic, "title", "(no title)"),
                        description=get_field(old_pic, "caption",
                                              "(no caption)"),
                        created=date,
                        modified=date,
                        visibility=Content.PUBLISHED)

            extension = {
                "image/jpeg": "jpg",
                "image/png": "png",
                "image/gif": "gif"
            }[get_field(old_pic, "mimeType")]
            file_name = "{}.{}".format(pic_id, extension)

            if reimport_files:
                file = File(
                    open("import/data/images/{}".format(file_name), 'rb'))
                pic.source.save(file_name, file, save=True)
Exemple #33
0
 def add_item(cls, request): 
     if request.method == 'POST':
         form = EshopItemForm(request.POST)
         if form.is_valid():
             #nowy BaseItem
             base_name = request.POST['name']
             base_category_name = request.POST['category']
             base_category = Category.objects.get(pk=base_category_name)
             #properties konstrukcja Json
             json = '{'
             properties = [[request.POST['properties1'], request.POST['pname1']], [request.POST['properties2'], request.POST['pname2']], [request.POST['properties3'], request.POST['pname3']], [request.POST['properties4'], request.POST['pname4']],
                           [request.POST['properties5'], request.POST['pname5']], [request.POST['properties6'], request.POST['pname6']]]
             i=0
             for property in properties:
                 if property[0]:
                     if i<len(properties) and i>0:
                         json = json + ',\r\n'
                     i = i+1
                     json = json + '"' + property[1] + '":"' + property[0] +'"'
                     
             json = json +'}'
                 
             #
             base_description = request.POST['description']
             base_thumb = request.FILES.get('thumb')
             base_is_active = request.POST['is_active']
             #
             new_base = BaseItem(name=base_name, properties=json, description=base_description, thumb=base_thumb, is_active=base_is_active)
             new_base.save()
             
             #images
             image1 = request.FILES.get('image1')
             new_image1 = Image(image=image1)
             if image1:                    
                 new_image1.save()
                 new_base.images.add(new_image1)
             image2 = request.FILES.get('image2')
             new_image2 = Image(image=image2)
             if image2:                    
                 new_image2.save()
                 new_base.images.add(new_image2)
             image3 = request.FILES.get('image3')
             new_image3 = Image(image=image3)
             if image3:
                 new_image3.save()
                 new_base.images.add(new_image3)
             
             #dodaj kategorie i obrazy 
             new_base.categories.add(base_category)                
             new_base.save()
             #nowy EshopItem
             price = request.POST['price']
             is_on_sale = request.POST.get('is_on_sale', False)
             discount_price = request.POST.get('discount_price')
             availiability_status_name = request.POST['availiability_status']
             availiability_status = AvailiabilityStatus.objects.get(pk=availiability_status_name)
             current_stock = request.POST['current_stock']
             
             new_eshopitem = EShopItem(price=price, is_on_sale=is_on_sale, discount_price=discount_price, availiability_status=availiability_status, current_stock=current_stock, base=new_base)
             new_eshopitem.save()
             return HttpResponseRedirect("/manager/sklep/")
     else:
         form = EshopItemForm(initial={"discount_price":0})
     return render_to_response('backpanel_new_item.html', 
                               {'form': form}, 
                               context_instance=RequestContext(request))
Exemple #34
0
 def process_image_pre_creation(self, django_settings, image_instance: PinImage):
     image_instance.image = get_new_image_field(image_instance.image.file)
    def handle_form_save(self, request, upload_form):
        """Save the data into database"""

        if upload_form.is_valid():
            try:
                PhotoObj = Photographer.objects.get(user_ref=request.user)
                if len(PhotoObj.image.all()):
                    for k in PhotoObj.image.all():
                        k.delete_image(os.path.join(MEDIA_ROOT, k.image.name))
                        k.delete()
                PhotoObj.home_page_desc = upload_form.cleaned_data[
                    'home_page_desc']
                # PhotoObj.image_1_desc = upload_form.cleaned_data['image_1_desc']
                # PhotoObj.image_2_desc = upload_form.cleaned_data['image_2_desc']
                # PhotoObj.image_3_desc = upload_form.cleaned_data['image_3_desc']
                PhotoObj.save()

                # image = Image(content_object=PhotoObj, image_name=upload_form.cleaned_data['image_1_name'])

                try:
                    image = Image(content_object=PhotoObj)
                    (image.image, image_name) = Image().copy_upload_image(
                        PhotoObj, upload_form.cleaned_data['image_1_name'],
                        request.user.username)
                    image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award1
                    image.image_a_name = image_name
                    image.image_desc = upload_form.cleaned_data['image_1_desc']
                    image.save()
                except Exception as e:
                    print str(e)
                    print "\n Inside Exception"
                    Image.objects.create(
                        content_object=PhotoObj,
                        image_name=IMAGE_NAME_CHOICES['TYPE'].Award1,
                        image_a_name=image_name,
                        image_desc=upload_form.cleaned_data['image_1_desc'])

                generate_version_add_watermark(image.image.name, 'thumbnail')

                image = Image(content_object=PhotoObj)
                (image.image, image_name) = Image().copy_upload_image(
                    PhotoObj, upload_form.cleaned_data['image_2_name'],
                    request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award2
                image.image_a_name = image_name
                image.image_desc = upload_form.cleaned_data['image_2_desc']
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')

                image = Image(content_object=PhotoObj)
                (image.image, image_name) = Image().copy_upload_image(
                    PhotoObj, upload_form.cleaned_data['image_3_name'],
                    request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Award3
                image.image_a_name = image_name
                image.image_desc = upload_form.cleaned_data['image_3_desc']
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')

                image = Image(content_object=PhotoObj)
                (image.image, image_name) = Image().copy_upload_image(
                    PhotoObj, upload_form.cleaned_data['profile_image_name'],
                    request.user.username)
                image.image_name = IMAGE_NAME_CHOICES['TYPE'].Profileimage
                image.image_a_name = image_name
                image.profile_image = True
                image.save()
                generate_version_add_watermark(image.image.name, 'thumbnail')

                return redirect("photographerprofile")

            except Exception as ex:
                raise Exception(str(ex))
        else:
            try:
                pass
                # if len(upload_form.cleaned_data['image_1_name']):
                #     dt = upload_form.cleaned_data['image_1_name']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_1_name'] = fn[0].split('/media/_versions/temp/')[1] + ln

                # if len(upload_form.cleaned_data['image_2']):
                #     dt = upload_form.cleaned_data['image_2']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_2_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_3']):
                #     dt = upload_form.cleaned_data['image_3']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_3_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_4']):
                #     dt = upload_form.cleaned_data['image_4']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_4_name'] = fn[0].split('/media/_versions/temp/')[1] + ln
                #
                # if len(upload_form.cleaned_data['image_5']):
                #     dt = upload_form.cleaned_data['image_5']
                #     fn = dt.split('_thumbnail')
                #     ln = fn[1]
                #     upload_form.cleaned_data['image_5_name'] = fn[0].split('/media/_versions/temp/')[1] + ln

            except Exception as e:
                pass

            return Response(
                {
                    'upload_form': upload_form,
                    'username': request.user.username
                },
                template_name='uploads.html')
Exemple #36
0
                          name=get_field(old_category, "url_name"),
                          title=get_field(old_category, "name"))
        section.save()

if ask_reimport("pictures"):
    Image.objects.all().delete()

    reimport_files = ask_reimport("image files")

    for old_pic in read_table("picture"):
        try:
            pic_id = get_field(old_pic, "id")
            date = read_date(get_field(old_pic, "date"))
            pic = Image(id=get_field(old_pic, "id"),
                        title=get_field(old_pic, "title", "(no title)"),
                        description=get_field(old_pic, "caption",
                                              "(no caption)"),
                        created=date,
                        modified=date)

            extension = {
                "image/jpeg": "jpg",
                "image/png": "png",
                "image/gif": "gif"
            }[get_field(old_pic, "mimeType")]
            file_name = "{}.{}".format(pic_id, extension)

            if reimport_files:
                file = File(
                    open("import/data/images/{}".format(file_name), 'rb'))
                pic.source.save(file_name, file, save=True)
            else:
Exemple #37
0
 def _update_start_parse_time(image: Image) -> None:
     image.start_parse_time = now()
     image.save()