def handle(self, *args, **options): checked = added = 0 images = Image.objects.values_list("phash", flat=True) galleries = Gallery.objects.values_list("slug", flat=True) gallery_path = os.path.join(settings.MEDIA_ROOT, "gallery") for root, dirs, f in os.walk(gallery_path): for dir in dirs: if dir not in galleries: gallery = Gallery(name=dir) gallery.save() else: gallery = Gallery.objects.get(slug=dir) for dir_root, d, files in os.walk(os.path.join(root, dir)): for file in files: file_name = os.path.join(dir_root, file) file_image = PILImage.open(file_name) file_phash = str(phash(file_image)) checked += 1 if file_phash not in images: image = Image(phash=file_phash, gallery=gallery) image.original_image.name = file_name.replace( settings.MEDIA_ROOT, "" )[1:] image.save() self.stdout.write("Saved %s" % image.original_image.name) added += 1 self.stdout.write("Checked %d images, added %d" % (checked, added))
def upload(request): if request.method == 'POST': g = Gallery(original = request.FILES['image'], title = request.POST['title'], description = request.POST['description']) g.save() img = Image.open(g.original.path) oldW, oldH = img.size oldRatio = oldW / float(oldH) newW = 100 newH = 100 newRatio = 1 left = (oldW - newW) / 2 top = (oldH - newH) / 2 right = (oldW + newW) / 2 bottom = (oldH + newH) / 2 path, f = os.path.split(g.original.name) if(newRatio > oldRatio): img = img.resize((newW, newW * oldH / oldW), Image.ANTIALIAS) else: img = img.resize((newH * oldW / oldH, newH), Image.ANTIALIAS) img.save(settings.MEDIA_ROOT + "uploads/preview/" + f) return HttpResponseRedirect("/gallery/lists") return render(request, 'upload.html')
def test_gallery_item_ajax_galleriffic(self): # create objects gallery = Gallery() gallery.save() gi_obj = GalleryImage(gallery=gallery, state='published') gi_obj.save() gi_obj.sites.add(Site.objects.get_current()) ve_obj = VideoEmbed(gallery=gallery, state='published') ve_obj.save() ve_obj.sites.add(Site.objects.get_current()) vf_obj = VideoFile(gallery=gallery, state='published', file='test.flv') vf_obj.save() vf_obj.sites.add(Site.objects.get_current()) # raise 404 on invalid slug self.assertRaises(Http404, views.gallery_item_ajax_galleriffic, request=None, slug='invalid_slug') # use galleryimage template for gallery image object client = Client() response = client.get(reverse('gallery_item_ajax_galleriffic', kwargs={'slug': gi_obj.slug})) self.assertTemplateUsed(response, 'gallery/ajax/galleriffic_galleryimage.html') # use videoembed template for video embed object response = client.get(reverse('gallery_item_ajax_galleriffic', kwargs={'slug': ve_obj.slug})) self.assertTemplateUsed(response, 'gallery/ajax/galleriffic_videoembed.html') # use videofile template for video file object response = client.get(reverse('gallery_item_ajax_galleriffic', kwargs={'slug': vf_obj.slug})) self.assertTemplateUsed(response, 'gallery/ajax/galleriffic_videofile.html')
def setUp(self): newGallery = Gallery() newGallery.gallery_image = SimpleUploadedFile(name='dan-hill.jpg', content=open('/Users/ZacheryTapp/weddingapp/weddingapp/weddingapp/weddingapp/assets/img/dan-hill.jpg', 'rb').read(), content_type='image/jpeg') newGallery.title = "gallery1" newGallery.alt_text = "gallery alt 1" newGallery.visibility = "Published" newGallery.display_order = "1" newGallery.save()
def save_model(self, request, obj, form, change): obj.created_by = request.user obj.modified_by = request.user if form.cleaned_data.get('image'): if obj.gallery: gallery_fk = obj.gallery gallery_fk.title = obj.title else: # gallery_fk = Gallery.objects.create() gallery_fk = Gallery(title=obj.title) gallery_fk.image = form.cleaned_data.get('image') gallery_fk.created_by = request.user gallery_fk.modified_by = request.user gallery_fk.save() obj.gallery = gallery_fk obj.save()
def save_model(self, request, obj, form, change): obj.created_by = request.user obj.modified_by = request.user if form.cleaned_data.get('image'): if obj.gallery: gallery_fk = obj.gallery gallery_fk.title=obj.title else: # gallery_fk = Gallery.objects.create() gallery_fk = Gallery(title=obj.title) gallery_fk.image=form.cleaned_data.get('image') gallery_fk.created_by=request.user gallery_fk.modified_by=request.user gallery_fk.save() obj.gallery = gallery_fk obj.save()
def add_gallery(request): if request.method == 'POST': form = AddGalleryForm(request.POST) if form.is_valid(): user = User.objects.get(pk=request.user.id) gallery = Gallery() f = request.FILES['image'] path = Upload_Image(filename=f) gallery.image = path gallery.user = user gallery.save() return HttpResponseRedirect('/') else: form = AddGalleryForm() return render_to_response('add_gallery.html', {'form':form}, context_instance=RequestContext(request, processors=[custom_proc]))
def edit_gallery(request, gallery_id=0): ''' Shows the new/edit gallery form and handles POST request ''' if request.method != 'POST': if gallery_id == 0: gallery = Gallery() else: gallery = get_object_or_404(Gallery, pk=gallery_id) if gallery.family_id != request.user.family_id: raise Http404 return render( request, 'gallery/edit_gallery.html', { 'gallery_id': gallery_id, 'gallery_title': gallery.title, 'gallery_description': gallery.description, }) else: family_id = request.user.family_id title = request.POST.get("title").strip() description = request.POST.get("description").strip() if gallery_id != 0: gallery = get_object_or_404(Gallery, pk=gallery_id) #Ensure cannot edit another persons family if gallery.family_id != family_id: raise Http404 gallery.title = title gallery.description = description gallery.save() else: gallery = Gallery.objects.create(family_id=family_id, title=title, description=description) return HttpResponseRedirect('/gallery={0}/'.format(gallery.id))
def test_video_file_response(self): # create a video file object gallery = Gallery() gallery.save() obj = VideoFile(gallery=gallery, file='test.flv') obj.save() # if the videofile_large photosize does not exist, use default dimensions (500x300) result = views.videofile_response({'object': obj}) self.failUnless('width:500px' in result) self.failUnless('height:300px' in result) # if the videofile_large photosize exists, use its dimension PhotoSize(name="videofile_large", width=606, height=340).save() obj = VideoFile(gallery=gallery, file='test.flv') obj.save() result = views.videofile_response({'object': obj}) self.failUnless('width:606px' in result) self.failUnless('height:340px' in result)
def _generate_file(self, instance): with ZipFile(instance.file.file, 'r') as zipObj: listOfFilename = zipObj.namelist(): for filename in listOfFilename: # read image file file = zipObj.read(filename) image = Image.open(BytesIO(file)) image.load() image = Image.open(BytesIO(file)) weigth, height = image.size # save content zip to db file_path = os.path.join(os.path.dirname(BASE_DIR), 'media/') + filename image.save(file_path, format="JPEG") galery = Gallery() galery.image = filename galery.name = filename galery.save()
def test_video_embed_response(self): original_embed = '<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/VdgI0j1odkY&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/VdgI0j1odkY&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>' correctly_modified_embed = '<object width="606" height="340"><param name="movie" value="http://www.youtube.com/v/VdgI0j1odkY&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/VdgI0j1odkY&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="606" height="340"></embed></object>\n' # create a video embed object gallery = Gallery() gallery.save() obj = VideoEmbed(gallery=gallery, embed=original_embed) obj.save() # if the videoembed_large photosize does not exist, return original unmodified embed result = views.videoembed_response({'object': obj}) self.failUnlessEqual(result, original_embed + '\n') # if the videoembed_large photosize exists, return original embed scaled to its dimensions PhotoSize(name="videoembed_large", width=606, height=340).save() obj = VideoEmbed(gallery=gallery, embed=original_embed, image="test.jpg") obj.save() result = views.videoembed_response({'object': obj}) self.failUnlessEqual(result, correctly_modified_embed)
def change_background_save(request): rspd = {} if request.method == "POST": client_response = request.POST['client_response'] fn = client_response.split('=')[1][8:] user = request.user user_profile = user.get_profile() if user_profile.background == fn: rspd['msg'] = u'不可重复保存' res = json.dumps(rspd) return HttpResponse(res) if user_profile.pp < 100: rspd['msg'] = u'保存失败,你的PP不足100。' res = json.dumps(rspd) return HttpResponse(res) g = Gallery(user=user, imagefile=fn) g.save() user_profile.background = fn user_profile.pp -= 100 user_profile.save() rspd['msg'] = u'保存成功' res = json.dumps(rspd) return HttpResponse(res)
def submit_article(request): ''' View for Article Submission ''' ImageFormset = formset_factory(ImageForm, extra=settings.MAX_NUM_IMAGES) if request.method == 'POST': form = ArticleSubmissionForm(request.POST, request.FILES) image_forms = ImageFormset(request.POST, request.FILES) if form.is_valid() and image_forms.is_valid(): title = request.POST['title'] subtitle = request.POST['subtitle'] body = request.POST['body'] editor = request.POST['editor'] authors = request.POST.get('authors', []) tags = request.POST.get('tags', []) files = request.FILES post_body = EnhancedText( body, editor) #Combines body and editor field to for creating post post = None if len(files) == 0: #Will save post as basic post post = BasicPost(title=title, slug=slugify(title), subtitle=subtitle, body=post_body) post.slug = post._get_unique_slug() post.save() elif len(files) == 1: #Will save post as post with simple image image = None image = files.itervalues().next() post = PostWithSimpleImage(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, image=image) post.save() else: #Will save post as post with slideshow gallery = Gallery(title=title) gallery.save() path = os.path.join(settings.MEDIA_ROOT, 'uploads') path = os.path.join(path, 'images') for index, image in enumerate(files): filename_unique = False filename = os.path.join(path, files[image].name) counter = 1 while not filename_unique: if os.path.exists(filename): filename_split = filename.split('.') filename = filename_split[0] extension = filename_split[1] filename = filename + unicode( counter) + '.' + extension else: filename_unique = True image_file = open(filename, 'wb+') for chunk in files[image].chunks(): image_file.write(chunk) image_file.close() filename_split = filename.split(os.sep) base_filename = filename_split[-1] filename = os.path.join('uploads', 'images') filename = os.path.join(filename, base_filename) image = Image(title=title, slug=slugify(title), file=filename) image.slug = image._get_unique_slug() image.save() ordered_image = OrderedImage(gallery=gallery, image=image, position=index) ordered_image.save() post = PostWithSlideshow(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, gallery=gallery) post.save() if post: # Saves the authors and tags of the post for index, author in enumerate(authors): credit = OrderedCredit( credit=Credit.objects.get(id=author), content_object=post, position=index) credit.save() for index, tag in enumerate(tags): tag = TaggedItem(tag=Tag.objects.get(id=tag), object=post) tag.save() article = SubmittedArticle(submitted_by=request.user, object=post) article.save() return HttpResponseRedirect(reverse('submit_article_success')) else: form = ArticleSubmissionForm() image_forms = ImageFormset() return render_to_response('submit_article/add.html', { 'form': form, 'image_forms': image_forms, 'max_forms': settings.MAX_NUM_IMAGES }, context_instance=RequestContext(request))
def submit_article(request): ''' View for Article Submission ''' ImageFormset = formset_factory(ImageForm, extra=settings.MAX_NUM_IMAGES) if request.method == 'POST': form = ArticleSubmissionForm(request.POST, request.FILES) image_forms = ImageFormset(request.POST, request.FILES) if form.is_valid() and image_forms.is_valid(): title = request.POST['title'] subtitle = request.POST['subtitle'] body = request.POST['body'] editor = request.POST['editor'] authors = request.POST.get('authors', []) tags = request.POST.get('tags', []) files = request.FILES post_body = EnhancedText(body, editor) #Combines body and editor field to for creating post post = None if len(files) == 0: #Will save post as basic post post = BasicPost(title=title, slug=slugify(title), subtitle=subtitle, body=post_body) post.slug = post._get_unique_slug() post.save() elif len(files) == 1: #Will save post as post with simple image image = None image = files.itervalues().next() post = PostWithSimpleImage(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, image=image) post.save() else: #Will save post as post with slideshow gallery = Gallery(title=title) gallery.save() path = os.path.join(settings.MEDIA_ROOT, 'uploads') path = os.path.join(path, 'images') for index, image in enumerate(files): filename_unique = False filename = os.path.join(path, files[image].name) counter = 1 while not filename_unique: if os.path.exists(filename): filename_split = filename.split('.') filename = filename_split[0] extension = filename_split[1] filename = filename + unicode(counter) + '.' + extension else: filename_unique = True image_file = open(filename, 'wb+') for chunk in files[image].chunks(): image_file.write(chunk) image_file.close() filename_split = filename.split(os.sep) base_filename = filename_split[-1] filename = os.path.join('uploads', 'images') filename = os.path.join(filename, base_filename) image = Image(title=title, slug=slugify(title), file=filename) image.slug = image._get_unique_slug() image.save() ordered_image = OrderedImage(gallery=gallery, image=image, position=index) ordered_image.save() post = PostWithSlideshow(title=title, slug=slugify(title), subtitle=subtitle, body=post_body, gallery=gallery) post.save() if post: # Saves the authors and tags of the post for index, author in enumerate(authors): credit = OrderedCredit(credit=Credit.objects.get(id=author), content_object=post, position=index) credit.save() for index, tag in enumerate(tags): tag = TaggedItem(tag=Tag.objects.get(id=tag), object=post) tag.save() article = SubmittedArticle(submitted_by=request.user, object=post) article.save() return HttpResponseRedirect(reverse('submit_article_success')) else: form = ArticleSubmissionForm() image_forms = ImageFormset() return render_to_response('submit_article/add.html', {'form': form, 'image_forms': image_forms, 'max_forms': settings.MAX_NUM_IMAGES}, context_instance=RequestContext(request))
def update_gallery(modeladmin, request, queryset): for pf in queryset: if pf.background: g = Gallery(user=pf.user, imagefile=pf.background) g.save()