def take_photo(request): data = request.POST.copy() if not request.user.is_authenticated(): return HttpResponseBadRequest('Only signed in users can upload photographs.') ctype = data.get("content_type") object_id = data.get("object_id") if ctype is None or object_id is None: return HttpResponseBadRequest("Missing content_type or object_id field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.get(id=object_id) except TypeError: return HttpResponseBadRequest("Invalid content_type value: %r" % escape(ctype)) except AttributeError: return HttpResponseBadRequest("The given content-type %r does not resolve to a valid model." % escape(ctype)) except ObjectDoesNotExist: return HttpResponseBadRequest("No object matching content-type %r and object PK %r exists." % (escape(ctype), escape(object_id))) form = PhotoForm(target, data=data, files=request.FILES) if not form.is_valid(): template_list = [ "photos/preview.html" #"comments/%s_%s_preview.html" % tuple(str(model._meta).split(".")), #"comments/%s_preview.html" % model._meta.app_label, ] return render(request, template_list, { "form" : form, } ) photo = form.save() #photo = form.get_photo_object() #photo.save() next = data.get("next", '/') return HttpResponseRedirect(next)
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 uploadImage(request): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): machineID = urllib2.unquote( request.POST['machineID'] ) scanner = Scanner.objects.get(uniqueId=machineID) person = scanner.owner imageFile = request.FILES['image'] code = getBarCodeFromImage(imageFile) if code == '': response = 'barcode not found' status = 'error' else: imageFile.name = getTmpFileName() response = updateRecords(code, person, imageFile) status = 'success' else: response = 'form is not valid' status = 'error' response_data = {'status': status,'response': response} return HttpResponse(json.dumps(response_data), mimetype="application/json")
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 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 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 add_photo(request,id): album=get_object_or_404(Item,id=id) if request.method=='POST': form=PhotoForm(request.POST,request.FILES ) if form.is_valid(): instance=form.save(commit=False) instance.item=album instance.save() return redirect(reverse('home')) form=PhotoForm() return render(request,'app/AddPhoto.html',{'form':form})
def post(self, request): photo = Photo(owner=request.user) form = PhotoForm(request.POST, instance=photo) if form.is_valid(): form.save() return redirect("photo_detail", photo.pk) context = {"form": form} return render(request, "photos/new_photo.html", context)
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 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 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 upload_photo(request): if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): photo = create_and_save_new_photo_with_thumb(request.user, form.cleaned_data['photo'].file.read(), form.cleaned_data['description']) return HttpResponse('photo uploaded') else: form = PhotoForm() return render_to_response(request, 'photo/upload.html', { 'form': form, })
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 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 photo_create(post_id): form = PhotoForm() form.post_id.data = post_id if form.validate_on_submit(): files = request.files.getlist('file') for file in files: photo = Photo() photo.upload(file, post_id) return redirect(url_for('house.article_show', id=post_id)) return render_template('photo_create.html', form=form)
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): 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 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 specificRecord(theId): # Get the record. aRow = db.session.query(ServiceRecord, Vehicle).filter_by(id=theId).join(Vehicle).first() aRecord = { "id": aRow[0].id, "year": aRow[1].year, "make": aRow[1].make, "model": aRow[1].model, "date": aRow[0].date, "miles": aRow[0].miles, "description": aRow[0].description } # Get the filepaths for the photos. import os aPostfix = "vehicles/receipts/{}".format(theId) aList = [url_for("static", filename=aPostfix + os.sep + x) for x in os.listdir("app/static/" + aPostfix)] # Create the form. aForm = PhotoForm() # Check to see if the form is valid as well as a post request. if aForm.validate_on_submit(): filename = secure_filename(aForm.upload.data.filename) aSavePath = 'app/static/vehicles/receipts/{}/'.format(theId) + filename aForm.upload.data.save(aSavePath) # Convert the photo to nice web stuff. from pgmagick import Image, InterlaceType aImg = Image(aSavePath) aImg.quality(80) aImg.scale("80%") aImg.interlaceType(InterlaceType.PlaneInterlace) aImg.write(aSavePath) flash("File uploaded", "success") aForm = PhotoForm() return render_template( "vehicles/record.html", theRecord=aRecord, theFiles=aList, theForm=aForm )
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 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 add_photo_view(request): if request.method == 'POST': form = PhotoForm(request.user, request.FILES, data=request.POST) if form.is_valid(): photo = form.save(commit=False) photo.owner = request.user photo.save() for tag in form.cleaned_data['tags']: photo.tags.add(tag) photo.save() if form.cleaned_data['tag']: tag = Tag(name=form.cleaned_data['tag'], owner=request.user) tag.save() photo.tags.add(tag) photo.save() return HttpResponseRedirect('/photos') else: form = PhotoForm(current_user=request.user) return render(request, 'photorizer/add_photo.html', {'form': form})
def upload(request): form = PhotoForm(auto_id="%s") if request.POST: form = PhotoForm( { "user": request.user.id, "pub_date": datetime.now(), "gallery": request.POST["gallery"], "title": request.POST["title"], }, request.FILES, ) if form.is_valid(): photo = form.save() photo.attach_tags(request.POST["tags"]) return render_to_response("photos/upload.html", {"form": form}, context_instance=RequestContext(request))
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 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_form.save() # guarda la foto messages.append('Foto guardada!! <a href="/photos/' + str(new_photo.pk) + '">Verfoto</a>') photo_form = PhotoForm() else: photo_form = PhotoForm() context = { 'form': photo_form, 'message_list': messages } return render(request, 'photos/new_photo.html', context)
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 create_photo(request): """ Gestiona la creacion de fotos :param request: objeto request :return: """ new_photo = None if request.method == "POST": 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 = { 'photo': new_photo, 'form': form } return render(request, 'create_photo.html', context)
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_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(): 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 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 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 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 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 photo_add(request): form = PhotoForm() errmsg = "" succ = False if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): p = Photo() p.title = form.cleaned_data['title'] p.description = form.cleaned_data['description'] p.datetime = datetime.datetime.now() p.uuid = str(uuid.uuid4()) p.license = form.cleaned_data['license'] p.published = form.cleaned_data['published'] p.featured = form.cleaned_data['featured'] p.extension = os.path.splitext(form.cleaned_data['photo'].name)[1][1:] p.notes = form.cleaned_data['notes'] p.postcard = form.cleaned_data['postcard'] p.save() p.set_tags(request.POST.getlist('tags')) create_new_photo_storage(photo=p, f=request.FILES['photo']) succ = p.id else: errmsg = form.errors return render(request, 'manage/photo-add.html', { 'NAV_PHOTO_CLASS': 'active', 'form': form, 'errmsg': errmsg, 'succ': succ, 'all_tags': get_all_tags(), } )
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 edit_album_view(request, a): ''' Allows users to edit albums ''' try: album = Album.objects.get(pk=a) except Album.DoesNotExist: raise Http404 if album.creator == request.user: if request.POST: photo = Photo(creator=request.user) photo_form = PhotoForm(request.POST, request.FILES, instance=photo) if photo_form.is_valid(): photo_form.save() photo.albums.add(album) photo.save() return HttpResponseRedirect('/edit/%s' % a) c = {} c.update(csrf(request)) context = {'c': c, 'album': album, 'PhotoForm': PhotoForm(), } message = 'Click texts to edit.' message += ' Click images to delete.' if \ len(album.photo_set.all()) > 0 else '' messages.info(request, message) return render(request, 'edit_album.html', context) raise PermissionDenied
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 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 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 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 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(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 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 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 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))
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))