def extract_photo(request, archive_file, photo, album): # zipfile and tarfile are inconsistent if isinstance(photo, ZipInfo): photo_filename = photo.filename extract_file = archive_file.open elif isinstance(photo, tarfile.TarInfo): photo_filename = photo.name extract_file = archive_file.extractfile else: raise TypeError("'photo' must be a ZipInfo or TarInfo object.") # Ignore directories if not os.path.basename(photo_filename): return # Generate unique filename num = album.photo_set.count() filename, extension = os.path.splitext(photo_filename) new_filename = str(num).zfill(4) + extension photo_obj = Photo() photo_obj.album = album try: with extract_file(photo) as f: photo_obj.file.save(new_filename, File(f)) if not save_photo(photo_obj): messages.add_message(request, messages.WARNING, _("{} is duplicate.").format(photo_filename)) except (OSError, AttributeError, UnidentifiedImageError): messages.add_message(request, messages.WARNING, _("Ignoring {}").format(photo_filename)) if photo_obj.file.path: os.remove(photo_obj.file.path) photo_obj.delete()
def post(self, req): """ Muestra un form para crear una foto y la crea si la peticion es POST :param req: HttpRequest :return: HttpResponse """ error_messages = [] success_message = "" # Creamos owner y se lo pasamos al form con un objeto pre-establecido photo_with_owner = Photo() photo_with_owner.owner = req.user form = PhotoForm(req.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() form = PhotoForm() success_message = "Foto guardada con éxito! " success_message += '<a href="{0}">'.format(reverse("photos_detail", args=[new_photo.pk])) success_message += "(ver foto)</a>" else: error_messages.append("Formulario incompleto.") context = {"form": form, "success_message": success_message} return render(req, "photos/new_photo.html", context)
def index(request): ''' the index view is responsible for managing user image uploads and outputing a list of all uploaded images ordered by ratings to the index.html template ''' if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): photo_name = form.cleaned_data['image_path'] new_img = Photo( image = photo_name, image_thumb = photo_name, name = photo_name, description = form.cleaned_data['image_desc'] ) new_img.save() return HttpResponseRedirect(reverse('photos:index')) else: form = ImageForm() photos_list = Photo.objects.all().order_by('-avg_rating', '-id') return render(request, 'photos:index', {'photos_list': photos_list, 'form': form})
def handle(self, *args, **options): if not os.path.isdir(options["folder"]): raise Exception("You must specify a directory to import") foldername = os.path.relpath(options["folder"]) album, date, title = foldername.split("_", maxsplit=2) date = parse_date("{}-{}-{}".format(date[:4], date[4:6], date[6:])) slug = slugify("-".join([str(date), title])) if Album.objects.filter(title=title, date=date).exists(): self.stdout.write( "An album with title ({}) and" " date ({}) already exists.".format(title, date) ) return self.stdout.write("Importing album '{}' ({})".format(title, str(date))) album = Album(title=title, date=date, slug=slug) album.save() n = 0 for filename in os.listdir(options["folder"]): try: photo = Photo(album=album) file = open(os.path.join(options["folder"], filename), "rb") photo.file.save(filename, File(file)) photo.save() n += 1 except Exception: self.stdout.write("Could not import {}".format(filename)) self.stdout.write("Imported {} photos from {}".format(n, options["folder"]))
def post(self, request): """ Crea una foto en base a la información POST :param request: HttpRequest :return: HttpResponse """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # asigno como propietario de la foto el usuario autenticado form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): # Guarda el objeto del formulario en la DB y lo devuelve new_photo = form.save() # Inicializamos formulario, con el reverse componemos la url dinámica que mostrará con la nueva # foto form = PhotoForm() success_message = 'Guardado con éxito!' success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = { # Pasamos en el context los datos que se mostrarán en el template 'form': form, 'success_message': success_message } return render(request, 'photos/new_photo.html', context)
def post(self, request, *args, **kwargs): # Ajax POST for file uploads if request.is_ajax(): custom_post = QueryDict('temp_hash=%s' % request.POST.get('temp_hash')) file_form = PhotoUploadForm(request.POST, request.FILES) print(request.POST) print(request.FILES) if file_form.is_valid(): # file_form.save() response = {'file': []} for photo in request.FILES.getlist('file'): # Create a new entry in our database new_image = Photo(image=photo, temp_hash=request.POST.get('temp_hash')) # Save the image using the model's ImageField settings new_image.save() response['file'].append({ 'name': '%s' % new_image.id, 'size': '%d' % request.FILES.__sizeof__(), 'url': '%s' % new_image.image.url, 'thumbnailUrl': '%s' % new_image.image.url, 'deleteUrl': '\/image\/delete\/%s' % new_image.id, "deleteType": 'DELETE' }) # return HttpResponse('{"status":"success"}', content_type='application/json') return JsonResponse(response) # return HttpResponse('{"status":"error: %s"}' % file_form.errors, content_type='application/json') return JsonResponse({'response': file_form.errors, }) return super(MultiAttachmentMixin, self).post(request, *args, **kwargs)
def test_get(self): Membership.objects.create( type=Membership.MEMBER, user=self.member, since=date(year=2015, month=1, day=1), until=None, ) for i in range(10): with open( os.path.join(settings.BASE_DIR, "photos/fixtures/thom_assessor.png"), "rb", ) as f: fi = SimpleUploadedFile( name="photo{}.png".format(i), content=f.read(), content_type="image/png", ) photo = Photo(album=self.album, file=fi) photo.save() response = self.client.get(reverse("photos:album", args=(self.album.slug,))) self.assertEqual(response.status_code, 200) self.assertEqual(response.context["album"], self.album) self.assertEqual(len(response.context["photos"]), 10)
def create(request): ''' Formulario para creacion de de foto (petición POST) param request: HttpRequest return: HttpResponse ''' success_message = '' if request.method == 'GET': form = PhotoForm() else: photo_with_owner = Photo() photo_with_owner.owner = request.user # Asignar como propietario de la foto al user autenticado form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() # Guarda el objeto y lo devuelve form = PhotoForm() # Al no pasar valores aparece el formulario vacio success_message = 'Guardado con éxito' success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk])) success_message += 'ver foto' success_message += '</a>' context = { 'form': form , 'success_message': success_message } return render(request, 'photos/new_photo.html', context)
def submit(request): PhotoFormSet = formset_factory(PhotoForm, extra=1) if request.method == 'POST': storyform = StoryForm(request.POST, request.FILES) photoformset = PhotoFormSet(request.POST, request.FILES) if storyform.is_valid() and photoformset.is_valid(): s = Story( title = storyform.cleaned_data['title'], moderator = request.user ) s.save(); for form in photoformset.cleaned_data: image = form['image'] p = Photo( name=s.title, story=s, image=image ) p.save() else: storyform = StoryForm() photoformset = PhotoFormSet() return render(request, 'stories/submit.html', {'storyfrom': storyform, 'photoformset': photoformset})
def upload_photos(request): if request.method == "POST": # get fields from page and build object files = request.FILES.getlist('images') description = request.POST['description'] title = request.POST['title'] pric = request.POST['price'] pub = request.POST.get('public', False) if (pub == 'on'): pub = False s_instance = Photoseries(title = title , description = description, owner=request.user ,price = pric, public = pub) # save series before adding images s_instance.save(False) # iterate over files for count,a_file in enumerate(files): # create & save Image for every file p_instance = Photo(title='Photoseries Photo', image=a_file, owner=request.user, public = pub) p_instance.save(True) # add image to series s_instance.images.add(p_instance) # save modified series s_instance.save() return redirect('/photoseries/list/') return render(request, 'photoseries/upload.html')
def post(self, request): """ Crea una foto en base a la documentacioón POST :param request: HttpRequest :param pk: id de la foto :return: HttpResponse """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # asigno como usuario de la foto, el usuario auteticado form = PhotoForm(request.POST, instance=photo_with_owner) # Instanciamos el formulario con los datos del POST if form.is_valid(): # Preguntar si es válido new_photo = form.save() # Guarda el objeto Photo y me lo devuelve form = PhotoForm() success_message = 'Guardado con éxito!' success_message += '<a href="{0}">'.format( reverse('photo_detail', args=[new_photo.pk]) ) success_message += 'Ver foto' success_message += '</a>' context = { 'form': form, 'success_message': success_message } return render(request, 'photos/new_photo.html', context)
def ghetto_fixtures(self): from os.path import abspath, dirname, join from django.contrib.auth.models import User from django.core.files import File from photos.models import Photo, PhotoSet fixtures_dir = join(abspath(dirname(__file__)), "fixtures") self.admin = User.objects.create_user('admin', '*****@*****.**', 's3cure!1') self.set = PhotoSet.objects.create(name="default") self.__photos = [] for i in range(1, 5): name = "photo_{0}.jpg".format(i) with open(join(fixtures_dir, name)) as f: p = Photo( title="Photo {0}".format(i), photo_set=self.set) p.image.save(name, File(f)) self.__photos.append(p) p.save() setattr(self, "photo_%d" % i, p)
def test_validation_fields(self): photo = Photo(name="") with self.assertRaises(IOError): photo.save() #@TODO:Criar teste para o upload usando o GoogleStorage
def post(self, request): success_message = '' number_of_photos_uploaded = self.get_number_of_photos_from_user( request) if not check_if_uploads_remaining(number_of_photos_uploaded): form = PhotoForm() success_message = 'Ya has subido 25 fotos. Has alcansado el limite.' else: photo_with_owner = Photo() photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() form = PhotoForm() success_message = 'Guardado con éxito' success_message += '<br>' success_message += '<br>' success_message += '<a href="{0}">'.format( reverse('photos_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = { 'form': form, 'success_message': success_message, 'nof': number_of_photos_uploaded, 'nof2': 25 - number_of_photos_uploaded } return render(request, 'photos/new_photo.html', context)
def post(self, request): """ Muestra un formulario :param request: :return: """ sucess_message = [] # Es esto seguro? -> Que pasa si meto owner con POST photo_with_owner = Photo() photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): photo = form.save() # Guarda el objeto y me lo devuelve sucess_message = 'Guardado con éxito ' sucess_message += '<a href=\"{0}\">'.format(reverse('photos_detail', args=[photo.pk])) sucess_message += 'Ver foto' sucess_message += '</a>' form = PhotoForm() context = { 'form': form, 'sucess_message': sucess_message } return render(request, 'photos/new_photo.html', context)
def send_photos(request): if request.method == 'POST': package = json.loads(request.body.decode('utf-8')) feedbacks = package['feedbacks'] category_id = package['categoryId'] product_id = package['productId'] for feedback in feedbacks: for image in feedback['images']: photo = Photo( url=image['url'], width=image['width'], height=image['height'], item_id=product_id, category_id=category_id, feedback_id=feedback['feedbackId'], ) try: photo.save() except Exception: pass response = HttpResponse("OK") add_access_control_headers(response) return response
def post(self, request): """ Crea una foto en base a la informacion POST :param request: HttpRequest :return: HttpResponse """ success_message = '' # Instancio el objeto photo_with_owner = Photo() # Asigno como propietario de la foto, al usuario que esta autenticado photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): # Guarda el objeto photo y me lo devuelve new_photo = form.save() form = PhotoForm() success_message = 'Guardado con éxito!' """No se debe usar new_photo.id, se debe usar pk. pk es la clave primaria que django identifica como id. El {0} nos indica el orden en el que van los argumentos """ success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = { 'form': form, 'success_message': success_message } return render(request, 'photos/new_photo.html', context)
def post(self, request): #Crea una instancia vacía de foto photo_with_owner = Photo() #Asigna los datos photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() #Guarda el objeto que viene en el formulario y lo devuelve #Poner todos los campos vacíos form = PhotoForm() success_message = 'Guardado con exito!' #reverse sirve para generar la url success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver Foto' success_message += '</a>' context = { 'form': form, 'success_message': success_message } return self.render(request, context)
def create(request): """ Show a form for create a new photo post. :param request: HttpRequest Object :return: HttpResponse Object """ success_message = '' if request.method == 'GET': #GET REQUEST form = PhotoForm() else: #POST REQUEST photo_with_owner = Photo() photo_with_owner.owner = request.user #Automatic asign user autenticated as owner form = PhotoForm(request.POST,instance=photo_with_owner) if form.is_valid(): new_photo = form.save() #Save the object photo and return it form = PhotoForm() #Empty form after submitting success_message = 'Photo created succesfully' success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk])) success_message += 'Take a look' success_message += '</a>' context = dict(form=form,success_message=success_message) return render(request,'photos/new_photo.html',context)
def upload(request): if request.method == 'POST': response = {'files': []} # Create a new entry in our database new_image = Photo(image_field=request.FILES['image_field']) # Save the image using the model's ImageField settings new_image.save() # Save output for return as JSON response['files'].append({ 'name': '%s' % new_image.id, 'size': '%d' % request.FILES.__sizeof__(), 'url': '%s' % new_image.image_field.url, 'thumbnailUrl': '%s' % new_image.image_field.url, 'deleteUrl': '\/image\/delete\/%s' % new_image.id, "deleteType": 'DELETE' }) print(response) return JsonResponse(response) form = PhotoUploadForm() context = { 'form': form, "class_name": form.__class__.__name__ } return render(request, "photos/upload.html", context)
def get_default_photo(self): try: return Photo.objects.filter(user_default=True)[0] except IndexError: user_fallback = "%s/photos/%s" % (settings.MEDIA_ROOT, "img_user_fallback.png") try: fp = open(user_fallback, "r") image = Image.open(fp) image.verify() photo = Photo(user_default=True) photo.save() Photo.objects.filter(pk=photo.pk).update(image="photos/img_user_fallback.png") photo = Photo.objects.get(pk=photo.pk) fp.close() return photo except: user_fallback = "%s/images/%s" % (settings.GLOBALS_STATIC_ROOT, "img_user_fallback.png") fp = open(user_fallback, "r") image = Image.open(fp) image.verify() fp2 = open(user_fallback, "r") target_file = File(fp2) name = "img_user_fallback.png" photo = Photo(user_default=True) photo.image.save(name, target_file, save=True) fp.close() fp2.close() return photo
def post(self, request): """ crea una foto en base a la información POST :param request: HttpRequest :return: HttpResponse """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user #asigno como propietario de la foto al usuario atuenticado form = PhotoForm( request.POST, instance=photo_with_owner ) #especificar instancia de foto a utilizar por el formulario if form.is_valid(): new_photo = form.save() #guarda el objeto Photo y me lo devuelves form = PhotoForm() success_message = '¡Guardado con éxito!' success_message += '<a href="{0}">'.format( reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = {'form': form, 'success_message': success_message} return render(request, 'photos/new_photo.html', context)
def post(self, request): #Crea una instancia vacía de foto photo_with_owner = Photo() #Asigna los datos photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save( ) #Guarda el objeto que viene en el formulario y lo devuelve #Poner todos los campos vacíos form = PhotoForm() success_message = 'Guardado con exito!' #reverse sirve para generar la url success_message += '<a href="{0}">'.format( reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver Foto' success_message += '</a>' context = {'form': form, 'success_message': success_message} return self.render(request, context)
def populate(request): for i in (1,2,3): p = Photo(name="test image #%s" % i, original_image="apps/photos/tests/test%s.jpg" % i) p.save() return HttpResponseRedirect("/photos")
def save_latest_flick_image(): flickr_image = get_latest_flickr_image() if not Photo.objects.filter(link=flickr_image['link']).exists(): photo = Photo(title=flickr_image['title'], link=flickr_image['link'], image_url=flickr_image['media']['m'], description=flickr_image['description']) photo.save()
def add_youtube_photo(client_upload_id, storage_id, author, album, now, youtube_id): def get_next_album_index(album): album_index_q = Photo.objects.filter(album=album).aggregate(Max("album_index")) max_album_index = album_index_q["album_index__max"] if max_album_index is None: return 0 else: return max_album_index + 1 success = False while not success: try: with transaction.atomic(): next_album_index = get_next_album_index(album) p, created = Photo.objects.get_or_create( storage_id=storage_id, defaults={ "photo_id": Photo.generate_photo_id(), "media_type": Photo.MEDIA_TYPE_YOUTUBE, "client_upload_id": client_upload_id, "subdomain": Photo.choose_random_subdomain(), "date_created": now, "author": author, "album": album, "album_index": next_album_index, "youtube_id": youtube_id, }, ) except IntegrityError: # This will happen if there is a collision with a duplicate # 'album_index' from a concurrent request success = False else: success = True if created: if not in_testing_mode(): # Update the photo servers: for photo_server in PhotoServer.objects.filter(subdomain=p.subdomain, unreachable=False): # TODO We should use concurrent requests for this num_retries = 5 initial_retry_time = 4 try: request_with_n_retries( num_retries, initial_retry_time, lambda: photo_server_set_photos(photo_server.photos_update_url, photo_server.auth_key, [p]), ) except requests.exceptions.RequestException: # TODO Log this photo_server.set_unreachable() album.save_revision(now, True) photos_added_to_album.send(sender=None, photos=[p.photo_id], by_user=author, to_album=album)
def form_valid(self, form): photo_name = form.cleaned_data['image_path'] new_img = Photo( image = photo_name, image_thumb = photo_name, name = photo_name, description = form.cleaned_data['image_desc'] ) new_img.save() return HttpResponseRedirect(reverse('photos:index'))
def multi_upload(request, album_id): if request.method == 'POST': owner = request.user print album_id gallery = get_object_or_404(Gallery, id=album_id) file = request.FILES[u'files[]'] error = False #文件是否合法 if file.size > MAX_FILE_SIZE: error = "maxFileSize" if file.size < MIN_FILE_SIZE: error = "minFileSize" if file.content_type not in ACCEPTED_FORMATS: error = "acceptFileTypes" if request.session["is_allow_upload"] == 0: error = "maxNumberOfFiles" else: request.session["is_allow_upload"] -= 1 response_data = { "name": file.name, "size": file.size, "type": file.content_type, } if error: response_data["error"] = error response_data = simplejson.dumps([response_data]) return HttpResponse(response_data, mimetype=response_mimetype(request)) #保存文件 image = Photo( title=file.name, description='description', image=file, owner=owner, gallery=gallery, ) image.save() response_data["url"] = image.image.url response_data['thumbnail_url'] = image.image['thumbnail'].url print 'url:',image.image['thumbnail'].url #删除链接 response_data["delete_url"] = "/photos/del/" + str(image.id) response_data["delete_type"] = "GET" response_data = simplejson.dumps({"files":[response_data]}) return HttpResponse(response_data, mimetype=response_mimetype(request)) else: request.session["is_allow_upload"] = MAXNUMBEROFFILES print request.session["is_allow_upload"] return render_to_response('photos/multi_upload.html',{ "open_tv":u'{%',"close_tv": u'%}',"maxfilesize": MAX_FILE_SIZE, "minfilesize": MIN_FILE_SIZE,"maxnumberoffiles":MAXNUMBEROFFILES, }, context_instance=RequestContext(request) )
def create_photo_model(self, name='testname', border_color="#FFFFFF", created_at=None): photo = Photo( owner=self.user, photo=self.create_image_file(), name=name, border_color=border_color, ) photo.save() if created_at is not None: Photo.objects.filter(pk=photo.pk).update(created_at=created_at) return photo
def post(self, request): photo = Photo() photo.owner = request.user form = PhotoForm(request.POST, instance=photo) if form.is_valid(): new_photo = form.save() messages.success( request, 'Foto creada correctamente con ID {0}'.format(new_photo.pk)) form = PhotoForm() context = {'form': form} return render(request, 'photos/new.html', context)
def save_latest_flickr_image(): """ We get the lastest image and save it to our Photo Model in the Database """ flickr_image = get_latest_flickr_image() # lets make sure we don't save the same image more than once # we are assuming each Flickr image has a unique Link if not Photo.objects.filter(link=flickr_image['link']).exists(): photo = Photo(title=flickr_image['title'], link=flickr_image['link'], image_url=flickr_image['media']['m'], description=flickr_image['description']) photo.save()
def form_valid(self, form): # I load these uploaded files into django-filer objects. files = Photo.objects.filter(temp_hash=self.request.POST.get('temp_hash')) # folder = Folder.objects.get(name='Customer Service') for f in files: new_file = Photo(image=f) # Save the image using the model's ImageField settings new_file.save() # Attach the new Filer files to the original form object. self.object.attachments.add(new_file) files.delete() return super(MultiAttachmentMixin, self).form_valid(form)
def upload(request): user = request.twitter_user if user is None: raise HTTPUnauthorized() if user.get('id') != request.registry.uploader_twitter_id: raise HTTPForbidden() media = request.POST.get('media') photo = Photo(media.type, request.POST.get('message', '')) photo.set_content(request.registry.photo_storage, media.file.read()) DBSession.add(photo) return dict(photo=photo, user_id=user['id'], user_screen_name=user.get('screen_name', ''))
def save_latest_flickr_image(): """ We get the lastest image and save it to our Photo Model in the Database """ flickr_image = get_latest_flickr_image() # lets make sure we don't save the same image more than once # we are assuming each Flickr image has a unique Link if not Photo.objects.filter(link=flickr_image['link']).exists(): photo = Photo( title=flickr_image['title'], link=flickr_image['link'], image_url=flickr_image['media']['m'], description=flickr_image['description'] ) photo.save()
def post(self, request): success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() form = PhotoForm() success_message = 'Imagen guardada con éxito! Ver ' success_message += '<a href="{0}">'.format( reverse('photo_detail', args=[new_photo.pk])) success_message += 'foto' success_message += '</a>' context = {'new_photo_form': form, 'success_message': success_message} return render(request, 'photos/new_photo.html', context)
def upload(request): file = upload_receive(request) instance = Photo(file=file) instance.save() basename = os.path.basename(instance.file.file.name) file_dict = { 'name': basename, 'size': instance.file.file.size, 'url': settings.MEDIA_URL + basename, 'thumbnail_url': settings.MEDIA_URL + basename, 'delete_url': reverse('jfu_delete', kwargs={'pk': instance.pk}), 'delete_type': 'POST', } return UploadResponse(request, file_dict)
def migrate_photo(old_buckets, s3_bucket, photo): print "Migrating photo: " + str(photo) old_photo_bucket = find_photo_bucket(old_buckets, photo.photo_id) new_subdomain = choose_random_subdomain() new_storage_id = Photo.generate_photo_id() print "New subdomain: " + new_subdomain print "New storage_id: " + new_storage_id def upload(ext): filename = os.path.join(settings.LOCAL_PHOTO_BUCKETS_BASE_PATH, old_photo_bucket, photo.photo_id + ext) print "Uploading: " + filename key = Key(s3_bucket, new_storage_id + ext) key.metadata = {"Content-Type": "image/jpeg"} key.set_contents_from_filename(filename) key.close() upload(".jpg") for ext in all_photo_extensions: upload("_" + ext + ".jpg") photo.subdomain = new_subdomain photo.storage_id = new_storage_id photo.save(update_fields=["subdomain", "storage_id"])
def post(self,request): success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user #Automatic asign user autenticated as owner form = PhotoForm(request.POST,instance=photo_with_owner) if form.is_valid(): new_photo = form.save() #Save the object photo and return it form = PhotoForm() #Empty form after submitting success_message = 'Photo created succesfully' success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk])) success_message += 'Take a look' success_message += '</a>' context = dict(form=form,success_message=success_message) return render(request,'photos/new_photo.html',context)
def import_photo(self, row, photographer): ''' Add or update a Photograph record from the given CSV row. ''' ret = None image = self.get_or_create_image(row) if not image: print('WARNING: image file not found {}'.format(row['filename'])) return ret created = False if not self.append_only: ret = Photo.objects.filter(image=image).first() if not ret: ret = Photo() created = True date_parts = _parse_date(row['date']) photo = { 'taken_year': date_parts.year, 'taken_month': date_parts.month, 'taken_day': date_parts.day, 'photographer': photographer, 'description': (row['description'] or ''), 'comments': row['comments'], 'image': image, } coords = row['dd_co_ordinates'] if coords: coords = coords.split() photo['location'] = Point(float(coords[1]), float(coords[0])) for field in photo: if photo[field]: setattr(ret, field, photo[field]) ret.save() _print_operation(ret, created, 'title') # Update or Create image file as Wagtail Image # .image_title = ~slugify(FILENAME) # .file = hash(FILE).jpg return ret
def handle(self, *args, **options): if not args: raise CommandError("The <photo_target_dir> argument is required") img_dir = os.path.join(settings.DJANGO_PROJECT_ROOT, args[0]) for fn in os.listdir(img_dir): if re.match(r'.+\.(png|jpg|gif)', fn) is not None: fp = os.path.join(img_dir, fn) self.stdout.write('Loading the photo "%s" ...' % fn) photo = Photo() photo.photo = photo.get_photo_path(fn) photo.photo.storage.save(photo.photo.name, File(open(fp))) photo.save() self.stdout.write('All photos loaded succesfully.')
def upload( request ): # The assumption here is that jQuery File Upload # has been configured to send files one at a time. # If multiple files can be uploaded simulatenously, # 'file' may be a list of files. file = upload_receive( request ) instance = Photo( file = file ) instance.save() basename = os.path.basename( instance.file.path ) file_dict = { 'name' : basename, 'size' : file.size, 'url': settings.MEDIA_URL + basename, 'thumbnailUrl': settings.MEDIA_URL + basename, 'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }), 'deleteType': 'POST', } return UploadResponse( request, file_dict )
def home(request): if request.user.is_authenticated(): return render(request, 'home.html', { 'photos': Photo.find_by_owner(request.user.id, limit=settings.PHOTOS_PER_PAGE, offset=0) #'photos': Photo.find_by_desc('sushi', 5, 0)[0] }) else: return login(request)
def create(self, request, raw=False, **kwargs): """ Uploads a new photo. """ title = request.CLEANED.get('title', '') description = request.CLEANED.get('description', '') if request.CLEANED['url']: photo = get_picture_from_url(request.CLEANED['url']) elif request.CLEANED['file64']: photo = request.CLEANED['photo'] else: if request.CLEANED['file']: uploaded_file = request.CLEANED['file'] format = request.CLEANED['format'] photo = Photo(user=request.user, title=title, description=description) photo.image.save("%s.%s" % (uuid.uuid4(), format), uploaded_file) photo.save() uploaded_file.close() return photo.to_json(request=request, detail=request.CLEANED['detail']) if not raw else photo
def save(self, commit=True, **kwargs): instance = super(GrowingPlaceForm, self).save(commit=False, **kwargs) instance.centroid = Point(self.cleaned_data['longitude'], self.cleaned_data['latitude']) # Intentionally ignoring commit keyword to save Photo instance.save() if self.cleaned_data['photo']: photo = Photo( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, original_image=self.cleaned_data['photo'] ) photo.save() return instance
def create_photo(self, album): photo = Photo() photo.album = album name = _generate_title() igen = IconGenerator(5, 5) # 5x5 blocks icon = igen.generate( name, 480, 480, padding=(10, 10, 10, 10), output_format="jpeg", ) # 620x620 pixels, with 10 pixels padding on each side photo.file.save(f"{name}.jpeg", ContentFile(icon)) photo.save()
def upload( request ): file = upload_receive( request ) instance = Photo( file = file ) instance.save() basename = os.path.basename( instance.file.file.name ) file_dict = { 'name' : basename, 'size' : instance.file.file.size, 'url': settings.MEDIA_URL + basename, 'thumbnail_url': settings.MEDIA_URL + basename, 'delete_url': reverse('jfu_delete', kwargs = { 'pk': instance.pk }), 'delete_type': 'POST', } return UploadResponse( request, file_dict )
def post(self, request): """ Crea una foto en base a la información POST """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # asigno como propietario de la foto el usuario autenticado form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() # Guarda el objeto y me lo devuelve form = PhotoForm() success_message = 'Guardado con éxito!' success_message += '<a href="' + reverse( 'photo_detail', args=[new_photo.pk]) + '">' success_message += 'Ver foto' success_message += '</a>' context = {'form': form, 'success_message': success_message} return render(request, 'photos/new_photo.html', context)
def create(request): success_message = "" if request.method == "GET": form = PhotoForm() else: photo_with_owner = Photo() photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() form = PhotoForm() url = reverse("photo_detail", args=[new_photo.pk]) success_message = "Guardado con éxito" success_message += f"<a href='{url}'>" success_message += "Ver foto" success_message += "</a>" context = {"form": form, "success_message": success_message} return render(request, 'photos/new_photo.html', context)
def handle(self, *args, **options): path = options['path'] for category in os.listdir(path): if category.startswith('.'): continue print 'Processing photos in category %s...' % category subfolder = os.path.join(path, category) for photo_name in os.listdir(subfolder): fh = open(os.path.join(subfolder, photo_name)) p = Photo(photo=File(fh)) p.save() p.metadata.category = category.lower() p.save() fh.close()
def _save_photo(request, username): create_time = request.POST['create_time'] latitude = request.POST['latitude'] longitude = request.POST['longitude'] location = request.POST['location'] image_name = request.POST['image_name'] image_type = request.POST['type'] description = request.POST['description'] _handle_uploaded_file(request.FILES['image_file'], os.path.join(UPLOAD_TO, image_name)) photo = Photo(username=username, create_time=create_time, latitude=latitude, longitude=longitude, location=location, image_name=image_name, type=image_type, description=description ) photo.save()
def new(request): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): photo = Photo( title = form.cleaned_data['title'], image = request.FILES['image'], user = request.user, ) photo.save() return HttpResponseRedirect(reverse('photos:index')) else: form = PhotoForm() return render_to_response( 'photos/new.html', {'form': form}, context_instance=RequestContext(request) )
def post(self, request): # Crea una foto en base a la informació POST success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # asigna como propietario form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() # Guarda el objeto y devuelve form = PhotoForm() success_message = '¡Guardado con éxito!' success_message += '<a ref="{0}">'.format(reverse('photos_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = { 'form': form, 'succes_message': success_message } return render(request, 'photos/new_photo.html', context)
def post(self, request): """ Muestra un formulario para crear una foto y la crea si la peticion es POST """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # asigno como propietario de la foto , al usuario autenicado form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() #guarda el objeto y devuelmelo form = PhotoForm() success_message = 'Guardado exitoso!!' success_message += '<a href="{0}">'.format( reverse('photos_detail', args=[new_photo.pk])) success_message += 'Ver Foto' success_message += '</a>' context = {'form': form, 'success_message': success_message} return render(request, 'photos/new_photo.html', context)
def post(self, request): """ Muestra un formulario para crear una foto y la crea si la peticion es POST :param request: :return: """ success_mesage = '' photo_with_owner = Photo() photo_with_owner.owner = request.user form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() #Guarda el objeto foto y se lo devuelve form = PhotoForm() success_mesage = 'Guardado con exito ' success_mesage += '<a href="{0}">'.format( reverse('photo_detail', args=[new_photo.pk])) success_mesage += 'Ver foto' success_mesage += '</a>' context = {'form': form, 'success_message': success_mesage} return render(request, 'photos/new.html', context)
def post(self, request): """ crea una foto en base a la información POST :param request: HttpRequest :return:HttpResponse """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user #Asigno como usuario de la foto, el usuario autenticado form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() form = PhotoForm() success_message = 'Guardado con éxito ' success_message += '<a href="{}">'.format( reverse('photo_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = {'form': form, 'success_message': success_message} return render(request, 'photos/new_photo.html', context)
def import_photos(request): path = settings.RAPIDSMS_APPS['receiver']['attachments_path'] # -> data/attachments def is_img(filename): return (filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png')) def not_in_db_already(filename): # Note that there's a query for each file here - another way would be to load all existing files to a list in one operation and work with that # but, that might generate huge list when there are a lot of photos in the DB, and might cause data freshness issues in some edge cases # so, we just do n queries each time (where n is probably not too big) instead return (Photo.objects.filter(original_image="%s/%s" % (path, filename)).count() == 0) files = os.listdir(path) img_files = filter(is_img, files) new_img_files = filter(not_in_db_already, img_files) for f in new_img_files: p = Photo(name=f, original_image="%s/%s" % (path, f)) p.save() return HttpResponseRedirect("/photos")
def upload(request): file = upload_receive(request) pet = PetProfile.objects.get(id=int(request.GET.get('pet_id'))) instance = Photo(image=file, pet=pet) instance.save() basename = os.path.basename( instance.image.path ) file_dict = { 'name' : basename, 'size' : file.size, 'photo_id': instance.id, 'url': settings.MEDIA_URL + 'photo/' + basename, 'thumbnailUrl': instance.thumbnail.url, 'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }), 'deleteType': 'POST', } return UploadResponse( request, file_dict )
def post(self, request): """ Crea la foto en base a la informacion del post :param request: HttpRequest :return: HttpResponse """ success_message = '' photo_with_owner = Photo() photo_with_owner.owner = request.user # Asigno como propietario de la foto al usuario autenticado actual form = PhotoForm(request.POST, instance=photo_with_owner) if form.is_valid(): new_photo = form.save() # Guarda el objeto y me lo devuelves form = PhotoForm() success_message = 'Foto guardada con exito!' success_message += '<a href="{0}">'.format(reverse('photos_detail', args=[new_photo.pk])) success_message += 'Ver foto' success_message += '</a>' context = { 'form': form, 'success_message': success_message } return render(request, 'photos/new_photo.html', context)