def upload_file(request): if request.method == 'POST': #form = UploadImageForm(request.POST, request.FILES) uploaded_name = request.FILES['pic'] #if form.is_valid(): pic = Picture(name="good", file = uploaded_name, date=datetime.datetime.now(), belongs_to="null", description="null") pic.save() return HttpResponseRedirect('/picture/') else: form = UploadImageForm() return render_to_response('upload.html', {'form': form} )
def upload(request): args = base_args_cabinet(request) form = AddJob(request.POST and request.FILES or None) if args['login']: user = get_user(request) if form.is_valid(): img = request.FILES['image_path'] p = Picture(user=user, name=img.name, path=img) p.save() return HttpResponseRedirect(reverse('cabinet:upload', args=())) args['form'] = AddJob({'author': user.pk}) return render(request, 'cabinet/upload.html', args) return HttpResponseRedirect(reverse('authsys:home_auth', args=()))
def test_import(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) motifs = set([tag.name for tag in picture.tags if tag.category == 'theme']) assert motifs == set([u'nieporządek']), 'theme tags are wrong. %s' % motifs picture.delete()
def test_import_with_explicit_image(self): picture = Picture.from_xml_file( path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml"), path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png"), ) picture.delete()
def test_import_2(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml"), path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png"), overwrite=True) cats = set([t.category for t in picture.tags]) assert 'epoch' in cats assert 'kind' in cats
def test_import_with_explicit_image(self): picture = Picture.from_xml_file( path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml"), path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png")) picture.delete()
def test_import_2(self): picture = Picture.from_xml_file( path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml"), path.join(path.dirname(__file__), "files/kandinsky-composition-viii.png"), overwrite=True) cats = set([t.category for t in picture.tags]) assert 'epoch' in cats assert 'kind' in cats
def import_picture(self, file_path, options, continue_on_error=True): try: image_store = ImageStore(os.path.dirname(file_path)) picture = Picture.from_xml_file(file_path, image_store=image_store, overwrite=options.get('force')) except Exception, ex: if continue_on_error: print "%s: %s" % (file_path, ex) return else: raise ex
def create(request): if request.method == "POST": print("request.FILES : {0}".format(request.FILES)) form = PictureForm(request.POST, request.FILES) print("form : {0}".format(form)) if form.is_valid(): # file is saved picture = Picture( title=form.cleaned_data["title"], description=form.cleaned_data["description"], file=request.FILES["file"], ) picture.save() return HttpResponseRedirect("/picture/") else: return render(request, "picture/new.html", {"form": form}) else: form = PictureForm() return render(request, "picture/index.html", {"form": form})
def test_import(self): picture = Picture.from_xml_file( path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) motifs = set( [tag.name for tag in picture.tags if tag.category == 'theme']) assert motifs == set([u'nieporządek' ]), 'theme tags are wrong. %s' % motifs picture.delete()
def upload(request): albums = Album.objects.order_by('-date')[:5] galleries = Gallery.objects.order_by('-date')[:5] context = {'albums': albums, 'galleries': galleries,} try: uploaded_name = request.FILES['pic'] except: return render(request, 'picture/upload.html', context) alb = Album.objects.get(pk = request.POST['album']) gal = Gallery.objects.get(pk = request.POST['gallery']) im = Image.open(uploaded_name) pic = Picture(name = request.POST['name'], file = uploaded_name, date_added=datetime.datetime.now(), date_last_edited=datetime.datetime.now(), belongs_to="null", description=request.POST['desc'], type = request.POST['tp'], album = alb, gallery = gal) pic.save() return HttpResponseRedirect('/media/')
def test_import(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) themes = set() for area in picture.areas.all(): themes.update([(tag.category, tag.name) for tag in area.tags if tag.category in (u"theme", u"thing")]) assert themes == {(u"theme", u"nieporządek"), (u"thing", u"Kosmos")}, "Bad themes on Picture areas: %s" % themes pic_themes = set([tag.name for tag in picture.tags if tag.category in ("theme", "thing")]) assert not pic_themes, "Unwanted themes set on Pictures: %s" % pic_themes picture.delete()
def picture_list(request, filter=None, template_name='catalogue/picture_list.html'): """ generates a listing of all books, optionally filtered with a test function """ pictures_by_author, orphans = Picture.picture_list() books_nav = SortedDict() for tag in pictures_by_author: if pictures_by_author[tag]: books_nav.setdefault(tag.sort_key[0], []).append(tag) # import pdb; pdb.set_trace() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def picture_list(request, filter=None, get_filter=None, template_name='catalogue/picture_list.html', cache_key=None, context=None): """ generates a listing of all books, optionally filtered with a test function """ if get_filter: filt = get_filter() pictures_by_author, orphans = Picture.picture_list(filt) books_nav = OrderedDict() for tag in pictures_by_author: if pictures_by_author[tag]: books_nav.setdefault(tag.sort_key[0], []).append(tag) return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def test_import(self): picture = Picture.from_xml_file(path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) themes = set() for area in picture.areas.all(): themes.update([(tag.category, tag.name) for tag in area.tags if tag.category in (u'theme', u'thing')]) assert themes == set([(u'theme', u'nieporządek'), (u'thing', u'kosmos')]), \ 'Bad themes on Picture areas: %s' % themes pic_themes = set([tag.name for tag in picture.tags if tag.category in ('theme', 'thing')]) assert not pic_themes, 'Unwanted themes set on Pictures: %s' % pic_themes picture.delete()
def test_import(self): picture = Picture.from_xml_file( path.join(path.dirname(__file__), "files/kandinsky-composition-viii.xml")) themes = set() for area in picture.areas.all(): themes.update([(tag.category, tag.name) for tag in area.tags if tag.category in (u'theme', u'thing')]) assert themes == {(u'theme', u'nieporządek'), (u'thing', u'Kosmos')}, \ 'Bad themes on Picture areas: %s' % themes pic_themes = set([ tag.name for tag in picture.tags if tag.category in ('theme', 'thing') ]) assert not pic_themes, 'Unwanted themes set on Pictures: %s' % pic_themes picture.delete()
def upload(request): # 获取post参数(图片) pic = request.FILES.get('pic') # 拼接图片存放路径, 必须是static/media下,有其他文件夹,就继续接 path = '%s/media/pic/%s' % (os.path.join(BASE_DIR, 'static'), pic.name) with open(path, 'wb') as f: for data in pic.chunks(): # 图片的内容有可能很大,需要循环读出来 f.write(data) # 保存路径到数据库 p = Picture() p.name = pic.name p.path = 'pic/%s' % pic.name p.save() return render(request, 'index.html')
def upload_handler(request): if request.method == "POST": f = request.FILES["upload"] filename = str(f) f_ext = os.path.splitext(str(f))[1] # If file is a compatible music file, build a filesystem structure for # it (media/artist-name/album-name), then write it to that location and # add details of the file to the database. if f_ext in [".mp3", ".MP3"]: with open(MEDIA_ROOT + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) filename = eyed3.load(MEDIA_ROOT + filename) dir_struct = MEDIA_ROOT + "music" + "/" + filename.tag.artist + "/" + filename.tag.album + "/" try: if not os.path.isdir(dir_struct): os.makedirs(dir_struct) shutil.move(MEDIA_ROOT + str(f), dir_struct) except OSError as ose: if ose.errno != 17: raise # Need to pass on Errno 17, due to race conditions caused # by making directories that already exist. pass except Exception as e: # File already exists. Remove the duplicate copy. os.remove(MEDIA_ROOT + str(f)) return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the artist or album doesn't exist in the database, create # table(s) for them. If they already exists, perform a query to # obtain an Artist or Album object for use as a foreign key. if not Artist.objects.filter(name=filename.tag.artist).exists(): artist = Artist(name=filename.tag.artist) artist.save() else: artist_set = Artist.objects.filter(name=filename.tag.artist) artist = [a for a in artist_set][0] if not Album.objects.filter(title=filename.tag.album).exists(): album = Album(title=filename.tag.album, artist=artist) album.save() else: album_set = Album.objects.filter(title=filename.tag.album) album = [a for a in album_set][0] if not Track.objects.filter(title=filename.tag.title).exists(): track = Track( title=filename.tag.title, album=album, artist=artist, fspath=dir_struct + str(f), media_url=MEDIA_URL + (dir_struct + str(f)).split(MEDIA_ROOT)[1], ) track.save() print "Added to DB: " + filename.tag.title return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".jpg", ".JPG"]: if not os.path.exists(MEDIA_ROOT + "pictures/" + str(f)): with open(MEDIA_ROOT + "pictures/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the picture doesn't exist in the database, add it. if not Picture.objects.filter(name=str(f)).exists(): picture = Picture( name=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "pictures/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "pictures/" + str(f)).split(MEDIA_ROOT)[1], ) picture.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) elif f_ext in [".mp4", ".MP4", ".m4v", ".M4V"]: if not os.path.exists(MEDIA_ROOT + "videos/" + str(f)): with open(MEDIA_ROOT + "videos/" + str(f), "wb") as destination: for chunk in f.chunks(): destination.write(chunk) else: # File already exists. Remove the duplicate copy. return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) # If the video doesn't exist in the database, add it. if not Video.objects.filter(title=str(f)).exists(): video = Video( title=os.path.splitext(str(f))[0], filename=str(f), fspath=MEDIA_ROOT + "videos/" + str(f), media_url=MEDIA_URL + (MEDIA_ROOT + "videos/" + str(f)).split(MEDIA_ROOT)[1], ) video.save() print "Added to DB: " + str(f) return render_to_response( "errors/upload_success.html", locals(), context_instance=RequestContext(request) ) else: return render_to_response( "errors/file_already_exists.html", locals(), context_instance=RequestContext(request) ) return render_to_response("errors/upload_failure.html", locals(), context_instance=RequestContext(request))
def add_product(request): categories = Category.objects.all() des_form = StandardDescriptionForm() context = { 'des_form': des_form, 'categories': categories, } if request.method == 'POST': print('POST: ', request.POST) print('FILES: ', request.FILES) persian_title = request.POST.get('persianTitle') english_title = request.POST.get('englishTitle') brand_name = request.POST.get('brand_name') price = request.POST.get('price') quantity = request.POST.get('quantity') cat = request.POST.get('select_categories') sub_cat1 = request.POST.get('levelone_placeholder') sub_cat2 = request.POST.get('leveltwo_placeholder') sub_cat3 = request.POST.get('levelthree_placeholder') image = request.FILES['image'] print() print(sub_cat1, sub_cat2, sub_cat3) print() category = Category.objects.filter(name=cat).first() if sub_cat3 != '-------------': sub_cat3_obj = SubCategory.objects.filter(name=sub_cat3).first() sub_category = sub_cat3_obj elif sub_cat2 != '-------------': sub_cat2_obj = SubCategory.objects.filter(name=sub_cat2).first() sub_category = sub_cat2_obj elif sub_cat1 != '-------------': sub_cat1_obj = SubCategory.objects.filter(name=sub_cat1).first() sub_category = sub_cat1_obj des_form = StandardDescriptionForm(request.POST) if des_form.is_valid(): description = des_form.save() b = Product( persian_title=persian_title, english_title=english_title, brand_name=brand_name, price=price, quantity=quantity, image=image, category=category, sub_category=sub_category, description=description, ) b.save() image_1 = request.FILES['image_1'] image_2 = request.FILES['image_2'] image_3 = request.FILES['image_3'] p1 = Picture(product=b, image=image_1) p2 = Picture(product=b, image=image_2) p3 = Picture(product=b, image=image_3) p1.save() p2.save() p3.save() else: des_form = StandardDescriptionForm() return render(request, 'dashboard/add_product.html', context)
def import_picture(self, file_path, options): picture = Picture.from_xml_file(file_path, overwrite=options.get('force')) return picture
def save(self, commit=True, **kwargs): return Picture.from_xml_file( self.cleaned_data['picture_xml_file'], image_file=self.cleaned_data['picture_image_file'], overwrite=True, **kwargs)
def fetch_picture(self): raw_page = requests.get(self.raw_url) if raw_page.headers['content-type'].startswith('image') : p = Picture(raw_url=self.raw_url,article=self) p.save()