def upload_view(request): message = None if request.method == "POST": try: form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data uploadImage = UploadImage(image=cd['image'], category=cd['category'], title=cd['title'], user=request.user) uploadImage.save() return HttpResponseRedirect("/") else: message = str(form.errors) except: if os.path.exists( os.path.join(settings.MEDIA_ROOT, cd['image'].path)): os.remove(os.path.join(settings.MEDIA_ROOT, cd['image'].path)) message = str(sys.exc_info()[1]) form = UploadImageForm() return render_to_response( register_path, RequestContext(request, { "message": message, "form": form }))
def images(request): """ view untuk menampilkan daftar images yang diupload user & mekanisme upload """ if request.POST: form = UploadImageForm(request.POST, request.FILES, initial={'user': request.user}) if form.is_valid(): if not request.user.has_perm('accounts.add_imageitem'): messages.error(request, _("Unvalidated user can not upload any images")) return HttpResponseRedirect(reverse('images')) title = form.cleaned_data['title'] image = form.cleaned_data['image'] ImageItem.objects.create(user=request.user, title=title, image=image) messages.info(request, _('Image Uploaded')) return HttpResponseRedirect(reverse('images')) else: form = UploadImageForm(initial={'user': request.user}) images_list = ImageItem.objects.filter(user=request.user) return render_to_response('accounts/images.html', {'form': form, 'images': images_list}, context_instance=RequestContext(request))
def process_image(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data['file'] tf = transformImage() data = tf.pre_process_img(img) results = tf.greyscale_to_ascii(data) # results contain result_white and result_black display_white = "\n" display_black = "\n" #convert the whole array into a string to avoid re-formatting for row in results[0]: # result_white for char in row: display_white += char display_white += "\n" request.session["display_white"] = display_white # store display_white into request session for row in results[1]: # result_black for char in row: display_black += char display_black += "\n" request.session["display_black"] = display_black # store display_black into request session request.session['display'] = display_white # by default, display white ascii art request.session["color"] = "white" else: print "uploading image failed" else: form = UploadImageForm() return render(request, 'asciiart/success.html')
def add_new_action(request, experience_id): """ Handle the file upload for a new action :param request: :param exp_id: The experience id linked to the action :return: """ user = get_object_or_404(User, id=request.user.id) exp = get_object_or_404(Experience, id=experience_id) action = Action(experience=exp, date_performed=datetime.now().strftime("%Y-%m-%d %H:%M")) if request.method == "POST": image_form = UploadImageForm(request.POST, request.FILES) comment_form = UploadCommentForm(request.POST) if not image_form.is_valid() and not comment_form.is_valid(): return render(request, 'webinator/error.html', {'error_id': "2"}) if image_form.is_valid(): image = image_form.save() action.photo = image if comment_form.is_valid(): comment = comment_form.save() action.comment = comment action.save() #return HttpResponseRedirect(reverse('action_list', args=[experience_id])) return HttpResponseRedirect(reverse('index')) else: return render(request, 'webinator/new_action.html', { 'image_form': UploadImageForm(), 'comment_form': UploadCommentForm() } )
def upload_file1(request): form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): img = request.POST.get("imageData", "") base64Image1 = base64.b64encode(form.cleaned_data['image'].read()) # print(base64Image) return render(request, 'app.html', {'form': UploadImageForm, 'image1': displayImage(base64Image1), 'ops': OperationsForm, 'imageData':img, 'imageData1':base64Image1})
def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) if image_form.is_valid(): request.user.save() return HttpResponse('{"status":"success","msg":"修改成功"}', content_type='application/json') else: return HttpResponse('{"status":"fail","msg":"修改失败"}', content_type='application/json')
def post(self, request): imageForm = UploadImageForm(request.POST, request.FILES, instance=request.user) res = {} if imageForm.is_valid(): imageForm.save() res['status'] = 'success' res['msg'] = '头像修改成功!' else: res['status'] = 'fail' res['msg'] = '头像修改失败!' return HttpResponse(json.dumps(res), content_type='application/json')
def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) # 文件类型需要第二个参数 if image_form.is_valid(): image_form.save() return HttpResponse('{"status":"success"}', content_type="application/json") else: return HttpResponse('{"status":"fail"}', content_type="application/json")
def upload_img(): form = UploadImageForm() if form.validate_on_submit(): pic = form.file.data filename = generate_filename(Image, secure_filename(pic.filename)) mimetype = pic.mimetype img = Image(filename=filename, img=pic.read(), mimetype=mimetype) db.session.add(img) db.session.commit() return redirect(f"{request.url_root}/admin/image/") return render_template("upload-img.html", form=form, logged_in=True)
def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) # 文件类型须传递这两个参数 if image_form.is_valid(): # image = image_form.cleaned_data['image'] # request.user.image = image # request.user.save() image_form.save() # 添加一个instance=request.user能够直接保存对象 return JsonResponse({"status": "success"}) else: return JsonResponse({"status": "fail"})
def index(request): if request.method == "POST": form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = UploadImageForm() images = EditorImage.objects.all().order_by("-created")[:10] return render_to_response('manager_index.html', {'form': form, 'images': images}, RequestContext(request))
def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) if image_form.is_valid(): # image = image_form.cleaned_data['image'] # request.user.image = image request.user.save() return HttpResponse('{"status":"success"}', content_type='application/json') else: return HttpResponse('{"status":"fail"}', content_type='application/json')
def upload_photo_ajax(request): """View for Uploading a photo.""" logger.info('Single image upload called by="'+str(request.user)+', ip='+str(request.META['REMOTE_ADDR'])) if request.user.is_authenticated(): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES or None) if form.is_valid(): image = form.save(commit=False) image.user=request.user image.save() form.save_m2m() try: default_album = get_object_or_404(Album, title="User's Posted") image.albums.add(default_album) except: logger.info('Error adding photo pk='+str(image.pk)+' to default album.') pass logger.info('Uploaded an image title="'+str(image.title)+', by user="******"') if notification: notification.send(User.objects.filter(is_superuser=True), "photo_add", {"ph_title":image.title,}) return HttpResponse(unicode("Uploaded success!")) else: #form errors return render_to_response("photo/upload_photo_form_for_ajax.html", {'form': form}) else: #get received form = UploadImageForm() return render_to_response("photo/upload_photo_form_for_ajax.html", {'form': form}) else: return HttpResponse(unicode('<div class="phtitle">Please log in to upload photos!</div>'))
def search(request): if request.method != 'POST': return render_ajax(request, 'GET is not supported') form = UploadImageForm(request.POST, request.FILES) if not form.is_valid(): return render_ajax(request, 'validate form failed') f = request.FILES['image'] if f.content_type not in [ 'image/jpeg', 'image/jpg', 'image/bmp', 'image/png' ]: return render_ajax(request, 'format not supported') filename = handle_uploaded_file(f) result = SearchService.search(filename, 0) return render_ajax(request, result=result)
def histogram(request): if request.method == 'GET': form = UploadImageForm return render(request, 'histogram.html', {'form': form}) elif request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): base64Image = base64.b64encode(form.cleaned_data['image'].read()) from histogram import Image2Histogram res = Image2Histogram(base64Image) return render( request, 'histogram.html', { 'form': UploadImageForm, 'image': displayImage(base64Image), 'result': res })
def negative(request): if request.method == 'GET': form = UploadImageForm return render(request, 'image_negative.html', {'form': form}) elif request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): base64Image = base64.b64encode(form.cleaned_data['image'].read()) from negative import negativeImage res = negativeImage(base64Image) return render( request, 'image_negative.html', { 'form': UploadImageForm, 'image': displayImage(base64Image), 'result': displayImage(res) })
def power(request): if request.method == 'GET': form = UploadImageForm return render(request, 'power-gamma.html', {'form': form}) elif request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): base64Image = base64.b64encode(form.cleaned_data['image'].read()) gamma = request.POST.get("gamma", "") from power_gamma import adjust_gamma res = adjust_gamma(base64Image, float(gamma)) return render( request, 'power-gamma.html', { 'form': UploadImageForm, 'image': displayImage(base64Image), 'result': displayImage(res) })
def submit(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) newImage = None if form.is_valid(): newImage = form.save(commit=False) newImage.img_hash = getHash() if request.user.is_authenticated(): newImage.uploaded_by = request.user newImage.save() request.session[newImage.img_hash] = True return redirect(reverse('images.views.view', kwargs={'img_hash': newImage.img_hash})) return render(request, "submit_post.html", {'newImage': newImage}) form = UploadImageForm() if request.GET.get('ref') == 'modal': return render(request, 'modal_form.html', {'title': 'Upload an Image', 'form': form}) else: return render(request, 'submit.html', {'form': form})
def equilisation(request): if request.method == 'GET': form = UploadImageForm return render(request, 'hist_equilisation.html', {'form': form}) elif request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): base64Image = base64.b64encode(form.cleaned_data['image'].read()) from hist_eq import histogram_equalization res, hist, eq_hist = histogram_equalization(base64Image) return render( request, 'hist_equilisation.html', { 'form': UploadImageForm, 'image': displayImage(base64Image), 'result': displayImage(res), 'hist': hist, 'eq': eq_hist })
def admin_edit_competition_page(id): form = EditCompetitionForm() imageForm = UploadImageForm() imageFolderPath = os.path.join(os.getcwd(), 'static/images/competitions') if (request.method == 'POST' and form.submit_competition.data or form.validate()): name = form.name.data date = form.date.data country = form.country.data description = form.description.data reward = form.reward.data image = imageForm.image.data filename = select("logo", "competition", "id={}".format(id)) if (image): extension = image.filename.split('.')[1] current_date = time.gmtime() filename = secure_filename("{}_{}.{}".format( id, current_date[0:6], extension)) filePath = os.path.join(imageFolderPath, filename) images = os.listdir(imageFolderPath) digits = int(math.log(int(id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(id)): os.remove(os.path.join(imageFolderPath, im)) image.save(filePath) elif (image): flash('Please upload a file in JPG format', "danger") print("Before update: ", date) update( "competition", "name='{}', date=DATE('{}'), country='{}', description='{}', reward='{}',logo='{}'" .format(name, date, country, description, reward, filename), "id={}".format(id)) return redirect( url_for('admin_edit.admin_edit_competition_page', id=id)) else: if (session.get('auth_type') != 'Team leader'): flash('No admin privileges...', 'danger') return redirect(url_for('home.home_page')) result = select('id,name,date,country,description,reward', 'competition, logo', 'id={}'.format(id))[0] form.description.data = result[4] return render_template('admin_edit_competition_page.html', form=form, result=result, imgName=result[5], uploadImg=imageForm) return render_template('admin_edit_competition_page.html', form=form, result=result, imgName=result[5], uploadImg=imageForm)
def upload_image(): form = UploadImageForm() if form.validate_on_submit(): image = form.image.data current_app.logger.debug(image) image_name = save_file(image,Path(current_app.instance_path).parent.joinpath('static/img') ) img = Image() img.name = image_name db.session.add(img) db.session.commit() current_app.logger.info(f'{image.name} saved to /static/images/') flash('image successfully uploaded', category='alert alert-success') return redirect(url_for('admin.homepage')) return render_template('admin/upload_image.html',form=form)
def equilisation(request): if request.method == 'GET': form = UploadImageForm return render(request, 'hist_equilisation.html', {'form': form}) elif request.method == 'POST': form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): base64Image = base64.b64encode(form.cleaned_data['image'].read()) from hist_eq1 import histogram_equalization res, x, y, z, x1, y1, z1 = histogram_equalization(base64Image) return render( request, 'hist_equilisation.html', { 'form': UploadImageForm, 'image': displayImage(base64Image), 'result': displayImage(res), 'x': x, 'y': y, 'z': z, 'x1': x1, 'y1': y1, 'z1': z1 })
def upload_view(request): message = None if request.method == "POST": try: form = UploadImageForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data uploadImage = UploadImage(image = cd['image'], category = cd['category'], title = cd['title'], user = request.user) uploadImage.save() return HttpResponseRedirect("/") else: message = str(form.errors) except: if os.path.exists(os.path.join(settings.MEDIA_ROOT, cd['image'].path)): os.remove(os.path.join(settings.MEDIA_ROOT, cd['image'].path)) message = str(sys.exc_info()[1]) form = UploadImageForm() return render_to_response(register_path, RequestContext( request, { "message": message, "form": form } ) )
def admin_edit_team_page(id): auth = session.get('auth_type') if (auth != 'admin' and (auth != 'Team leader' and id != session.get('team_id'))): flash('No admin privileges...', 'danger') return redirect(url_for('home.home_page')) form = EditTeamForm() competitions = select("id,name", "competition") form.competition.choices = competitions imgForm = UploadImageForm() imgFolder = os.path.join(os.getcwd(), 'static/images/team') if (request.method == 'POST' and form.submit_team.data or form.validate()): name = form.name.data members = form.memberCtr.data year = form.year.data email = form.email.data address = form.address.data competition = form.competition.data image = imgForm.image.data if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( id, date[0:6], extension)) filePath = os.path.join(imgFolder, filename) images = os.listdir(imgFolder) digits = int(math.log(int(id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(id)): os.remove(os.path.join(imgFolder, im)) image.save(filePath) update("team", "logo='{}'".format(filename), "id={}".format(id)) elif (image): flash("Please upload a file in JPG format", 'danger') update( "team", "name='{}', num_members={}, found_year='{}', email='{}', adress='{}', competition_id={}" .format(name, members, year, email, address, competition), where="id={}".format(id)) return redirect(url_for('admin_edit.admin_edit_team_page', id=id)) else: result = select( columns= "team.name,team.num_members,team.found_year,team.email,team.adress,team.logo,competition.id", table= "team left outer join competition on team.COMPETITION_ID=competition.id", where="team.id={}".format(id)) print("EDIT TEAM RESULT", result) form.name.data = result[0] form.memberCtr.data = result[1] form.year.data = result[2] form.email.data = result[3] form.address.data = result[4] img_name = result[5] form.competition.data = result[6] return render_template('admin_edit_team_page.html', form=form, result=result, uploadImg=imgForm, imgName=img_name) return render_template('admin_edit_team_page.html', form=form, result=result, uploadImg=imgForm, imgName=img_name)
def admin_edit_member_page(person_id): # TODO:: Alter table to include social accounts links in person database. auth = session.get('auth_type') if (auth != 'admin'): flash("No admin", 'danger') return redirect(url_for("home.home_page")) form = EditMemberForm() subteams = select( "subteam.id,subteam.name", "subteam join team on subteam.team_id=team.id join person on person.team_id=team.id", "person.id={}".format(person_id)) form.subteam.choices = subteams majors = select("major.id,major.name", "major") form.major.choices = majors auth_types = select("id,name", "auth_type") form.auth_type.choices = auth_types cvForm = UploadCVForm() cvPath = None cvFolder = os.path.join(os.getcwd(), 'static/cv') imgForm = UploadImageForm() imgPath = None imgFolder = os.path.join(os.getcwd(), 'static/images/person') member_id = select("member.id", "member join person on person.id=member.person_id", where="person.id={}".format(person_id))[0] if form.validate_on_submit(): team = form.team.data subteam = form.subteam.data role = form.role.data auth_type = form.auth_type.data email = form.email.data name = form.name.data address = form.address.data active = form.active.data age = form.age.data phone = form.phone.data clas = form.clas.data major = form.major.data cv = cvForm.cv.data image = imgForm.image.data if (cv and '.pdf' in cv.filename): date = time.gmtime() filename = secure_filename("{}_{}.pdf".format( person_id, date[0:6])) cvPath = os.path.join(cvFolder, filename) cvs = os.listdir(cvFolder) digits = int(math.log(int(person_id), 10)) + 1 for c in cvs: if (c[digits] == '_' and c[0:digits] == str(person_id)): os.remove(os.path.join(cvFolder, c)) cv.save(cvPath) update("person", "cv='{}'".format(filename), "id={}".format(person_id)) session['person_id'] = person_id elif (cv): flash("Upload a PDF file.", 'danger') if (image and '.jpg' in image.filename or '.jpeg' in image.filename or '.png' in image.filename): date = time.gmtime() extension = image.filename.split('.')[1] filename = secure_filename("{}_{}.{}".format( person_id, date[0:6], extension)) imgPath = os.path.join(imgFolder, filename) images = os.listdir(imgFolder) digits = int(math.log(int(person_id), 10)) + 1 for im in images: if (im[digits] == '_' and im[0:digits] == str(person_id)): os.remove(os.path.join(imgFolder, im)) image.save(imgPath) update("member", "picture='{}'".format(filename), "id={}".format(member_id)) elif (image): flash("Please upload a file in JPG format", 'danger') teamID = select(columns="id", table="team", where="name='{}'".format(team))[0] majorID = select(columns="id", table="major", where="id='{}'".format(major))[0] update("member", "role='{}', active={}, address='{}'".format( role, active, address), where="id={}".format(member_id)) update("person", "name='{}', age='{}', phone='{}',email='{}', \ class={}, auth_type={}, team_id={}, subteam_id={}, major_id={}".format( name, age, phone, email, clas, auth_type, teamID, subteam, majorID), where="id={}".format(person_id)) return redirect( url_for('admin_edit.admin_edit_member_page', person_id=person_id, cvPath=person_id)) else: result = select( "person.name,person.email,team.name,subteam.id,member.role,member.active, \ member.entrydate,auth_type.id,member.address,person.phone,major.id, \ person.class,person.age,person.cv,member.picture", "person join member on member.person_id=person.id \ join team on person.team_id=team.id \ join subteam on person.subteam_id=subteam.id \ join auth_type on person.auth_type=auth_type.id \ join major on person.major_id=major.id ", "person.id={}".format(person_id)) form.name.data = result[0] form.email.data = result[1] form.team.data = result[2] form.subteam.data = result[3] form.role.data = result[4] form.active.data = result[5] form.entry.data = result[6] form.auth_type.data = result[7] form.address.data = result[8] form.phone.data = result[9] form.major.data = result[10] form.clas.data = result[11] form.age.data = result[12] cvPath = result[13] img_name = result[14] return render_template('admin_edit_member_page.html', form=form, uploadImg=imgForm, uploadCV=cvForm, cvPath=cvPath, imgName=img_name)