def create_photo(request): """ Gestiona la creación de una nueva foto :param request: objeto request :return: objeto response """ new_photo = None if request.method == 'POST': # si le hemos dado al boton crear, vamos a validar el formulario y a guardar la foto photo_with_user = Photo(owner=request.user) # creamos foto para el usuario autenticado form = PhotoForm(request.POST, instance=photo_with_user) # Le indicamos que en lugar de instanciarse una foto propio, # use new_photo que tiene ya asignado un usuario if form.is_valid(): new_photo = form.save() # guardamos la foto en la base de datos form = PhotoForm() #para que nos borre la info que ya habíamos metido en el formulario else: # si no, creamos un formulario vacio form = PhotoForm() context = { 'form' : form, 'photo' : new_photo } return render(request, 'photos/create_photo.html', context)
def UploadPhoto(request): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save(request.user) return HttpResponseRedirect("/upload/") else: return render_to_response("upload.html", {'form': form, 'STATIC_URL': settings.STATIC_URL,}, RequestContext(request)) form = PhotoForm() return render_to_response("upload.html", {'form': form, 'STATIC_URL': settings.STATIC_URL,}, RequestContext(request))
def create(request): if request.method == "GET": form = PhotoForm() elif request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): obj = form.save() return redirect(obj) ctx = { 'form': form, } return render(request, 'edit.html', ctx)
def upload(request): """ Upload view function. Saves new photos or display upload form. """ if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): # handle_uploaded_file(request.FILES['image']) photo = form.save(commit=False) photo.create(request.user) return HttpResponseRedirect('/view/%s/' % photo.id) else: form = PhotoForm() return render_to_response('upload.html', locals(), context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): """ Handles the upload of photos and returns a JSON serialization of the uploaded photo. """ photoForm = PhotoForm(request.POST, request.FILES) if photoForm.is_valid(): # check that the file size is valid: image_file_size = photoForm.files['image'].size if image_file_size <= MAX_UPLOAD_SIZE: # save the photo and image file: photo = photoForm.save(commit=False) # set the default caption and user: photo.caption = photo.image.name photo.user = request.user photo.save() # return the serialized photo: return { 'status': 'success', 'status_code': 200, 'photoData': photo.serialize(), } # return error response return { 'status': 'invalid', 'status_code': 403, }
def job_photo(request, job_id): ''' Takes and stores a photo for a job ''' variables = {} form_data = {} form_data['job'] = variables['job_id'] = job_id form = PhotoForm(initial=form_data) if request.POST: form = PhotoForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, 'Photo successfully added.') variables['form'] = form return render(request, 'contractor/take-photo.html', variables)
def create_photo(request): new_photo = None if request.method == 'POST': #Creamos la foto para el usuario autenticado photo_with_user = Photo(owner=request.user) form = PhotoForm(request.POST, instance=photo_with_user) if form.is_valid(): new_photo = form.save() form = PhotoForm() else: form = PhotoForm() context = {'form': form, 'photo': new_photo} return render(request, 'photos/create_photo.html', context)
def upload(request): form = PhotoForm(request.POST or None, request.FILES or None) if form.is_valid(): new_photo = form.save(commit=False) new_photo.user = request.user new_photo.save() return redirect('index') return locals()
def create_photo(request): """ Gestiona la creacion de fotos :param: request: :return: """ new_photo = None if request.method == 'POST': photo_with_user = Photo( owner=request.user) # creamos foto para el usuario form = PhotoForm(request.POST, instance=photo_with_user) if form.is_valid(): new_photo = form.save() form = PhotoForm() else: form = PhotoForm() context = {'form': form, 'photo': new_photo} return render(request, 'photos/create_photo.html', context)
def gallery(request, gallery_id): try: gallery = Gallery.objects.get(id=gallery_id) except Gallery.DoesNotExist: raise Http404 if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): new_photo = form.save(commit=False) new_photo.visible_by = 'AD' new_photo.save() form.save_m2m() return HttpResponseRedirect("/gallery/%s/" % gallery_id) else: form = PhotoForm() context = {'gallery': gallery, 'form': form} return render(request, "gallery.html", context)
def upload(request, id): if not request.user.is_staff and not request.user.is_superuser: return HttpResponseForbidden( 'You should be authenticated as admin or staff to upload files') article = get_object_or_404(Article, id=id) form = PhotoForm(request.POST, request.FILES) if form.is_valid(): p = form.save(commit=False) p.article = article p.save() return HttpResponse('')
def post_photo(request, project_id): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): p = Project.objects.get(id=project_id) image = form.cleaned_data['file'] ph = Photo.objects.create(image=image) p.photos.add(ph) p.save() return JsonResponse({"data": "success"}) print form.errors
def new_photo(request): messages = [] if request.POST: # lo mismo que hacer request.method == 'POST' photo_with_user = Photo(owner=request.user) photo_form = PhotoForm(request.POST, files=request.FILES, instance=photo_with_user) if photo_form.is_valid(): #new_photo = Photo() #new_photo.url = photo_form.cleaned_data.get('url') #... #new_photo.save() new_photo = photo_form.save() # guarda la foto messages.append('Foto guardada! <a href="/photos/' + str(new_photo.pk) + '">Ver foto</a>') photo_form = PhotoForm() else: photo_form = PhotoForm() context = {'form': photo_form, 'message_list': messages} return render(request, 'photos/new_photo.html', context)
def post_photo(username, album_id): user = User.query.filter_by(username=username).first() album = Album.query.filter_by(id=album_id).first() form = PhotoForm() if request.method == 'POST' and form.validate(): new_photo = Photo(caption=form.caption.data, image=form.image.data, album_id=album.id) db.session.add(new_photo) db.session.commit() flash('Photo successfully uploaded') return redirect(url_for('photos', username=username, album_id=album_id)) return render_template('new_photo.html', user=user, album=album, form=form)
def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): f = form.save(commit=False) contractor = Contractor.objects.get(pk='1025362') f.content_type = ContentType.objects.get(model='contractor') f.object_id = contractor.LicNum # print('test2') f.save() data = {'is_valid': True, 'name': f.img.name, 'url': f.img.url} else: # print('test3') data = {'is_valid': False} return JsonResponse(data)
def photos(username): if request.method == 'GET': return render_template('photos.html', profile_user=User.get_user(username), photo_form=PhotoForm()) else: if not (g.user and g.user.username == username): flash("You are not authorized for that action.") return redirect('views.profiles') photo_form = PhotoForm() if photo_form.validate_on_submit(): filename = PHOTO_UPLOAD_SET.save(photo_form.photo.file) photo = Photo(filename, g.user.id) db.session.add(photo) db.session.commit() flash("Photo saved.") return redirect(url_for('views.photos', username=g.user.username)) return render_template('photos.html', profile_user=g.user, username=g.user.username, photo_form=photo_form)
def edit_photo(photo_id=None): form = PhotoForm() print(form.capture_date) photo = None title = "Whats the pic about" if photo_id is not None: photo = Photograph.query.filter(Photograph.id == photo_id).first() if photo is None: photo = Photograph(status="DRAFT") if request.method == 'POST': if form.validate_on_submit(): photo_id = update_photo(form, photo) return redirect(url_for("posts.edit_photo", photo_id=photo_id)) if request.method == "GET": form = PhotoForm(id=photo.id, title=photo.title, photograph_url=photo.photograph_url, tag_ids=photo.all_tag_ids(), capture_date=photo.capture_date, location=photo.location) title = photo.title return render_template('edit_photo.html', title=title, form=form)
def add_photo(request): if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): try: photo = Photo.objects.get(user=request.user) string = handle_uploaded_file(request.FILES['photo'], request.user) t, e = splitext(request.FILES['photo'].name) #im = Image.open('./media/user_pics/%s%s'%(request.user.username,e)) #photo.photo = Image.open('./user_pics/%s%s'%(request.user.username,e)) photo.extension = e photo.save() request.user.message_set.create(message="Photo modifiée.") return render_to_response('users/add_photo.html', {'form': form}, RequestContext(request)) except Photo.DoesNotExist: string = handle_uploaded_file(request.FILES['photo'], request.user) t, e = splitext(request.FILES['photo'].name) #img = Image.open('./user_pics/%s%s'%(request.user.username,e)) #photo = Photo(user=request.user,photo=img,extension=e) photo = Photo(user=request.user, extension=e) photo.save() request.user.message_set.create(message="Photo ajoutée.") return render_to_response('users/add_photo.html', {'form': form}, RequestContext(request)) else: return render_to_response('users/add_photo.html', {'form': form}, RequestContext(request)) else: form = PhotoForm() return render_to_response('users/add_photo.html', {'form': form}, RequestContext(request))
def photo_upload(): photoform = PhotoForm() if request.method == 'POST' and photoform.validate_on_submit(): photo = photoform.photo.data # we could also use request.files['photo'] description = photoform.description.data filename = secure_filename(photo.filename) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return render_template('display_photo.html', filename=filename, description=description) flash_errors(photoform) return render_template('photo_upload.html', form=photoform)
def upload_photo(request): form = PhotoForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): name = request.POST['product_name'] desc = request.POST['product_desc'] image = request.FILES['uploaded'] new_image = Photo(title=name, photo=image, description=desc) new_image.save() #response for testing purposes sResponse = {"SUCCESS": "1", "MESSAGE": "Upload was Successfull"} return HttpResponse(simplejson.dumps(sResponse), content_type='application/json') sResponse = {"SUCCESS": "0", "MESSAGE": "Upload was Not Successfull"} return HttpResponse(simplejson.dumps(sResponse), content_type='application/json')
def upload_image(): user = get_current_user() form = PhotoForm() if form.validate_on_submit(): file = form.photo.data if file and allowed_file(file.filename): filename = secure_filename(rename_file(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) try: old_file = 'static/img/' + user.photo_file_name os.remove(old_file) except OSError: pass with pg_db.atomic(): img_q = User.update(photo_file_name=filename).where(User.username == user.username) img_q.execute() flash('Your profile photo has been changed') return redirect(url_for('profile', username=user.username)) return render_template('upload_image.html', form=form, title='Change your avatar')
def upload(): form = PhotoForm() if form.validate_on_submit(): f = form.photo.data filename = str(uuid.uuid1()) + '_' + secure_filename(f.filename) logging.debug('filename:: %s' % filename) logging.debug('path:: %s' % os.path.join( UPLOAD_PATH, filename ) ) f.save(os.path.join( UPLOAD_PATH, filename )) #return redirect(url_for('upload')) flash("Image uploaded successfully !") return render_template('upload.html', form=form) error = None if 'photo' in form.errors: error = form.errors['photo'] return render_template('upload.html', form=form, error=error)
def submit(): form = PhotoForm() if request.method == 'POST': if form.validate_on_submit(): try: form.handle_submit(request) flash('Your picture has been sent successfully!', 'success') return redirect(url_for('submit')) except: flash_message = 'An internal error occured. Sorry...' if (DEBUG): import sys e = sys.exc_info() flash_message += ' DEBUG : (' + str(e[1]) + ')' flash(flash_message, 'danger') else: flash( 'Invalid form. Only jpg, jpeg, png and tiff files are allowed !', 'danger') return render_template('submit.html', form=form)
def add_point(request): """ Get the form to add a point """ data = {'success': False} rendered = None form = PointForm(request.POST or None, request.FILES if request.POST else None) if request.method == 'POST': point = form.save(commit=False) point.user = request.user point.save() photoForm = PhotoForm(request.POST, request.FILES) photo = photoForm.save(commit=False) photo.point = point photo.save() else: rendered = render_to_string('points/add_point_form.html', {'form': form}, RequestContext(request)) data = {'success': True, 'html': rendered} return HttpResponse(simplejson.dumps(data))
def post(self, request, *args, **kwargs): """ Handles the updating of photos and returns a JSON serialization of the updated photo. Note, this view cannot update the associated image file. """ public_id = kwargs.get('public_id') photo = get_object_or_404(Photo, public_id=public_id) photoForm = PhotoForm(request.POST, instance=photo) if photoForm.is_valid(): # save the photo: photo = photoForm.save() # return the serialized photo: return { 'status': 'success', 'status_code': 200, 'photoData': photo.serialize(), } # return error response return { 'status': 'invalid', 'status_code': 403, }
def generic_photos(request, model, object_id, max_photos=5, extra_context={}): model_instance = get_object_or_404(model, pk=object_id) photos = GenericPhoto.objects.photos_for_object(model_instance) if request.method == 'POST' and photos.count() < max_photos: form = PhotoForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) if instance.image.size > photos_settings.MAX_PHOTO_SIZE: messages.error(request, _(u'The photo is too big.')) os.unlink(instance.photo.path) return HttpResponseRedirect( request.META.get('HTTP_REFERER', '/')) # ext = os.path.splitext(os.path.split(instance.get_photo_filename())) # if ext != '.png' and ext != '.jpg' and ext != '.gif': # _flash_message(request, _(u'El solo fotos de tipo: PNG, JPG o GIF son permitidas.'), type='error') # os.unlink(instance.get_photo_filename()) # return HttpResponseRedirect('/photos/' + str(ad.number)) instance.object_id = object_id instance.content_type = ContentType.objects.get_for_model(model) instance.save() photos = GenericPhoto.objects.photos_for_object(model_instance) if photos.filter(main=True).count() == 0: new_main_photo = photos[0] new_main_photo.main = True new_main_photo.save() messages.success(request, _(u'The photo was added successfully.')) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) else: form = PhotoForm() extra_context.update({ 'title': _(u'photos for%(object_name)s%(max_photos)s: %(object)s') % { 'object_name': ' %s' % unicode(extra_context['object_name']) if 'object_name' in extra_context else '', 'object': model_instance, 'max_photos': (_(u' (maximum of %s)') % max_photos if max_photos else '') }, 'object': model_instance, 'object_list': photos, 'hide_object': True, 'extra_columns': [{ 'name': _(u'photo'), 'attribute': lambda x: '<div class="gallery"><a href="%s"><img src="%s" /></a></div>' % (x.get_display_url(), x.get_thumbnail_url()) }, { 'name': _(u'main photo'), 'attribute': lambda x: '<span class="famfam active famfam-accept"></span>' if x.main else '-' }, { 'name': _(u'title'), 'attribute': lambda x: x.title if x.title else '-' }], }) if GenericPhoto.objects.photos_for_object( model_instance).count() < max_photos: extra_context.update({ 'subforms_dict': [ { 'name': 'generic_form_subtemplate.html', 'title': _(u'Upload new photo'), 'form': form, }, ], }) else: #subform_dict is persistent between views, clear it explicitly extra_context.update({'subforms_dict': []}) return render_to_response('photos.html', extra_context, context_instance=RequestContext(request))