Example #1
0
def index():

    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():

        bucket_name = app.config['BUCKET_NAME']
        key = uuid.uuid4()
        filename = str(key) + '.ics'
        fullpath = '/' + bucket_name + '/' + filename

        upfile = request.files['csv_file']

        try:
            ics_file = converter.convert(upfile)

        except (ContentError, HeadersError, DatetimeFormatError) as error:
            flash(error, 'danger')
            return render_template('index.html', form=form, links=base_links,
                                   links_title=links_title)

        else:
            mtype = 'text/calendar'
            with gcs.open(fullpath, 'w', content_type=mtype) as w:
                w.write(ics_file)

            session['key'] = key
            return redirect(url_for('success'))

    for field, errors in form.errors.items():
        for error in errors:
            msg = "Whups! {}".format(error)
            flash(msg)
    return render_template('index.html', form=form, links=base_links,
                           links_title=links_title)
Example #2
0
def upload():
    form = UploadForm()
    if form.validate():
        if form.title.data == "":
            flash("Must include title")
            return redirect(request.referrer + "#add_form")
        filename = secure_filename(form.photo.data.filename)
        pos = filename.rfind('.')
        #flash(str(filename[pos + 1: ] in ALLOWED_EXTENSIONS))
        if pos < 0 or (pos >= 0 and (not filename[pos + 1 : ] in ALLOWED_EXTENSIONS)):
            flash("Error: Invalid extension, pleases use jpg or png")
            return redirect(request.referrer + '#add_form')
        form.photo.file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        pin = Pin(title=form.title.data,
                  img=filename,
                  dscrp=form.dscrp.data,
                  orig=True,
                  date=datetime.now(),
                  pinner=current_user.to_dbref(),
                  repins=0,
                  like_count=0)
        pin.save()
        flash("Image has been uploaded.")
    else:
        flash("Image upload error.")
    return redirect(request.referrer + "#add_form" or url_for("index"))
Example #3
0
def index():
    subtitle = "Transfer books to Internet Archive"
    form = UploadForm(request.form)
    if request.method == "POST":
        if form.validate():
            book_id = html_escape(form.book_id.data)
            email = html_escape(form.email.data) if form.email.data not in (None, "") else ""
            book = bridge.fields(form.library_id.data, book_id, email)
            book_id = book.Id if book.Id not in (None, "") else book_id
            redis = redis_py.Redis()
            redis_key3 = keys.redis_key3
            book_key = "%s:%s:%s" % (redis_key3, form.library_id.data, book_id)
            library_url_key = book_key + ":library_url"
            redis_py.set(library_url_key, form.book_id.data, True)
            redis.expire(library_url_key, 60 * 15)
            verification_status_no = book.verify_fields()
            if verification_status_no != 0:
                flash(error_msg(verification_status_no, book))
                return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
            else:
                if redundant_request(book) == True:
                    flash(error_msg(50))
                    return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
                book_info = bridge.book_info(form.library_id.data, book_id)
                if isinstance(book_info, (int, long, float, complex)):
                    flash(error_msg(book_info))
                    return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
                confirm_resp = make_response(minify(render_template("confirm.html", book_info=book_info, form=form)))
                uuid = urandom(32).encode("hex")
                confirm_resp.set_cookie("bub_session", uuid)
                store_request(book, uuid)
                return confirm_resp
        return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
    else:
        return render_template("index.html", subtitle=subtitle, libraries=libraries, form=form)
Example #4
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        try:
            name = form.name.data
            filename = images.save(form.image.data, folder=unicode(g.user.id))

            #Checks if Image is new or exists before commit changes
            image = Image.query.filter_by(name = form.name.data).first()
	    if image is None:
                image = Image(name = name, filename = filename, uid=g.user.id)
                message = "%r image uploaded." % name
            else:
                old_file = image.filename
                image.filename = filename
                message = "%r image changed." % name

            db.session.add(image)
            db.session.commit()

            flash(message)
            return redirect(url_for('index'))
        except UploadNotAllowed:
            flash("Not allowed to upload image")
    else:
        filename = None

    return render_template('upload.html',
        form = form,
        filename = filename)
 def get_form(self):
     if 'key' in request.args:
         if request.endpoint == "photos":
             self.page.assets['new_photo'] = request.args['key']
             self.form = PostForm()
             self.form.photo.data = self.page.assets['new_photo']
             self.template = "post_form.html"
         else:
             self.page.assets['new_photo'] = request.args['key']
             self.form = EditForm()
             self.form.photo.data = self.page.assets['new_photo']
             self.form.about_me.data = g.user.about_me
             self.form.nickname.data = g.user.nickname
             self.template = "update_photo.html"
     else:
         if request.is_xhr:
             if request.endpoint == "photos":
                 self.form = UploadForm(prefix="").s3_upload_form()
         else:
             if request.endpoint == "photos":
                 key = "user-images/" + str(g.user.id) + "/" + str(uuid4()) + ".jpeg"
                 message = "Select New Photo"
                 redirect_url = request.base_url
             else:
                 key = "user-images/" + str(g.user.id) + "/profile_image/" + str(uuid4()) + ".jpeg"
                 message = "Change Profile Picture"
                 redirect_url = request.base_url
             self.form = UploadForm(key=key, message=message, redirect_url=redirect_url).s3_upload_form()
Example #6
0
File: views.py Project: cainlu/exjp
def judge_action(request):
    form = UploadForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        context = data['context']
        if '_auth_user_id' in request.session:
            user_id = request.session['_auth_user_id']
            user = User.objects.get(id=user_id)
        else:
            user = None
        if request.FILES.has_key('image'):
            image = request.FILES['image']
        else:
            image = None
        if image != None and image.size > 3 * 1024 * 1024:
            return render_to_response('result.jinja', {'state':'2', 'message':u'图片最大3M', 'url':'/main/upload'}, RequestContext(request))
        item = Item.objects.create(
                                   user=user,
                                   context=context,
                                   time=datetime.now(),
                                   image=image,
                                   status=0,
                                   agree=random.randint(100, 200),
                                   disagree=random.randint(0, 50),
                                   score=int(time.time() / (60 * 60) * 1000),
                                   )
        item.save()
        return render_to_response('result.jinja', {'state':'1', 'message':u'上传成功', 'url':'/main/upload'}, RequestContext(request))
    else:
        for field in form:
            if field.errors:
                return render_to_response('result.jinja', {'state':'2', 'message':field.errors, 'url':'/main/upload'}, RequestContext(request))
Example #7
0
def upload_file():
    form = UploadForm()

    if request.method == "POST":
        if form.validate() == False:
            flash("All fields are required.")
            return render_template("upload.html", form=form)
        else:
            file = request.files["filename"]
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
                msg = Message(form.subject.data, sender="*****@*****.**", recipients=["*****@*****.**"])
                msg.body = """
                From: %s <%s>
                Subject: %s
                PeakCaller: %s
                SupplementalInfo: %s
                File Name: %s
                """ % (
                    form.name.data,
                    form.email.data,
                    form.subject.data,
                    form.peakcaller.data,
                    form.supplementalinfo.data,
                    filename,
                )
                mail.send(msg)
                return redirect(url_for("uploaded_file", filename=filename))
    elif request.method == "GET":
        return render_template("upload.html", form=form)
Example #8
0
def editCustomerCodes(customer_id=None):

    form = UploadForm()

    if form.validate_on_submit() and form.filename.data:
        file = form.filename.data
        filename = 'cust_' + str(customer_id) + '.csv'
        file.save(os.path.join(CUSTOMER_CODES_PATH, filename))
        try:
            parse_csv(os.path.join(CUSTOMER_CODES_PATH, filename))
            flash(gettext('CSV uploaded and processed sucessfully.'))
        except:
            flash(gettext('Upload unsuccessful! File could not be parsed!'))
        redirect('/settings/editcustomercodes')

    def_file_path = getCustomerCodesDefinitionFiles(customer_id)
    if def_file_path:
        try:
            def_file_data = parse_csv(def_file_path[0])
        except:
            def_file_data = []
    else:
        def_file_data = []
    customer = Customer.query.get(customer_id)

    return render_template('/settings/editcustomercodes.html',
                           title=gettext("Edit Customer Codes"),
                           customer=customer,
                           def_file_data=def_file_data,
                           form=form)
Example #9
0
def upload_img(request):
	form = UploadForm()
	if request.method == 'POST':
		form = UploadForm(request.POST, request.FILES)
		if form.is_valid():
			if not os.path.isdir(app_settings['DIC_UPLOAD_FULL']):
				os.makedirs(app_settings['DIC_UPLOAD_FULL'])
			
			filename = "%s.%s" % (get_file_code(), form.cleaned_data['image'].name.split('.')[-1])
			filepath = os.path.join(app_settings['DIC_UPLOAD_FULL'], filename)
			fileurl = '%s%s' % (app_settings['DIC_IMG_URL'], filename)
			f = open(filepath, 'wb+')
			for chunk in form.cleaned_data['image'].chunks():
				f.write(chunk)
			f.close()
			image = Image.open(filepath)
			if image.size[0] > app_settings['DIC_IMG_SIZE'][0] and image.size[1] > app_settings['DIC_IMG_SIZE'][1]:
				image.thumbnail(app_settings['DIC_IMG_SIZE'], Image.ANTIALIAS)
			print filepath
			image.save(filepath)
			width_b = image.size[0]
			height_b = image.size[1]
			
			width = int(request.GET.get('w'))
			height = int(request.GET.get('h'))
			
			return HttpResponseRedirect('%s?filename=%s&w=%s&h=%s&wb=%s&hb=%s' % (reverse('dic-crop-img'), filename, width, height, width_b, height_b))
	return render_to_response('django_img_crop/upload-img.html', {'form': form, 'is_popup': True}, context_instance=RequestContext(request))
Example #10
0
def handleImagePopAdd(request, addForm, field, template="form/popmediaadd.html"):
    if not request.method == "POST":
        f = UploadForm()
        ctx = {'form': f, 'field': field}
        return render(request, template, ctx)

    f = UploadForm(request.POST, request.FILES)

    if not f.is_valid() and not request.FILES['file'].name.endswith('.svg'):
        ctx = {'form': f, 'field': field}
        return render(request, template, ctx)
    file = request.FILES['file']
    store_in_s3(file.name, file.read())
    p = Image(url="http://%s.s3.amazonaws.com/%s" % (bucket, file.name))

    if isinstance(request.user, AnonymousUser):
        p.user = User.objects.get(username="******")
    else:
        p.user = User.objects.get(username=request.user)
    if request.POST['artist']:
        p.artist = User.objects.get(pk=request.POST['artist'])
    p.save()
    newObject = p

    # Self destruction:
    if newObject:
        return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' %\
            (escape(newObject._get_pk_val()), escape(newObject)))
Example #11
0
def upload():
    if g.user.files.count() >=100:
        flash("You can't upload more than 100 files")
        return redirect(url_for('index'))
    form=UploadForm()
    if form.validate_on_submit():
        file=form.file.data
        filename = secure_filename(file.filename)
        #create sha1 of file
        url=sha1(file.read()).hexdigest()
        f=File.query.filter_by(url=url).first()
        if f is None:
            file.seek(0)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], url))
        else:
            if f.own==g.user:
                flash('File already exist in your storage(%s)'%f.name)
            else:
                flash("File already exist(%s in %s's storage)"%(f.name,f.own.nickname))
        newfile=File(url=url,timestamp=datetime.datetime.utcnow(),name=filename,own=g.user)
        db.session.add(newfile)
        db.session.commit()
        return redirect(url_for('index'))

    return render_template('upload.html',form=form)
Example #12
0
def upload_file(request):
	resp = {}
	url = str(request.get_full_path())	
	pid = url.split("/")[-1]
	try:	
		if request.method == 'POST':
			form = UploadForm(request.POST, request.FILES)
			if form.is_valid():
				#获取表单信息
				xlsfile = form.cleaned_data['Filedata']
				filename = xlsfile.name
				#写入数据库
				uf = Upload(Filedata = xlsfile, uptime = datetime.datetime.now()) 
				uf.save()
				filepath = uf.Filedata
				uipath = unicode(str(filepath), "utf8")
				uipath = os.path.join(settings.MEDIA_ROOT,uipath)
				excel_table_byindex(request,file= uipath, pid = pid)
				resp['success'] = True
		else:
			form = UploadForm()
	except Exception,e:
		info = "%s" % (sys.exc_info()[1])
		resp['success'] = False
		resp['message'] = info
Example #13
0
def upload(request):
    if request.method == "POST":
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            subject = form.cleaned_data["subject"]
            message = form.cleaned_data["message"]
            attach2 = request.FILES["attach"]
            sender = form.cleaned_data["sender"]
            cc_myself = form.cleaned_data["cc_myself"]
            recipient = ["*****@*****.**"]
            if cc_myself:
                recipient.append(sender)

            try:
                mail = EmailMessage(subject, message, sender, recipient, ["EMAIL_ADDRESS"])
                mail.attach(attach2.name, attach2.read(), attach2.content_type)
                mail.send()

            except:
                return "Attachment error"

            return HttpResponseRedirect(reverse("feel_home"))
    else:
        # Dynamic initial values.
        form = UploadForm(initial={"sender": "Email address"})
    return render(request, "upload.html", {"form": form})
Example #14
0
def upload():
    form = UploadForm()
    if request.method == 'POST' and form.validate():
        g.user.avatar = form.uri.data
        db_session.add(g.user.avatar)
        db_session.commit()
        return redirect(url_for("home", username=g.user.username))
    return render_template("upload.html", form=form, user=g.user)
Example #15
0
def upload():
    if not current_user.is_admin():
        return 'Not Authorized', 500
    form = UploadForm(request.form)
    if form.validate_on_submit():
        #save and process it
        pass
    return render_template('upload.html', form=form)
Example #16
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        flash('Upload success.')
        session['filenames'] = [filename]
        return redirect(url_for('show_images'))
    return render_template('upload.html', form=form)
Example #17
0
def upload():
    """Render the website's about page."""
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        data_file = request.files['file']
        file_name = secure_filename(data_file.filename)
        data_file.save(os.path.join(UPLOAD_FOLDER, file_name))
        save_form_data(request.form, file_name)
        return redirect(url_for('thanks'))
    return render_template('upload.html', form=form)
Example #18
0
def upload_file(request):
	msg = ''
	if request.method == 'POST':
		form = UploadForm(request.POST,request.FILES)
		if form.is_valid():
			user_capacity = User_capacity.objects.get(user=request.user)
			form = form.cleaned_data
			the_file = form['upload_file']
			user_name = request.user.username
			size = the_file.size
			capacity = user_capacity.capacity
			if capacity - size < 0:
				msg = 'Su archivo no pudo ser subido, excede su capacidad de almacenamiento (%s)' % (str(user_capacity))
				data = {'form':UploadForm(initial={'choices':'privado'}),
						'msg':msg}
				return render(request,'upload_file.html',data)
			scale = 'B'
			if size > 1048576: # mayor a 1 MB
				size = size / 1048576.0
				scale = 'MB'
			elif size > 1024: # mayor a 1 KB
				size = size / 1024.0
				scale = 'KB'
			filepath = os.path.join(settings.BASE_DIR,'BajarCaja','uploads',user_name+'_files',the_file.name)
			if not os.path.exists(os.path.dirname(filepath)):
				os.makedirs(os.path.dirname(filepath))
			with open(filepath, 'wb') as destination:
				for chunk in the_file.chunks():
					destination.write(chunk)
			file_db = File(
						filename=the_file.name,
						upload_date=datetime.now(),
						filepath=filepath,
						size=size,
						real_size=the_file.size,
						scale_sz = scale,
						public=form['choices']=='publico',
						user=request.user)
			file_db.save()
			user_capacity.capacity = capacity - the_file.size
			if user_capacity.capacity >= 1048576: # mayor a 1 MB
				user_capacity.capacity_show = user_capacity.capacity / 1048576.0
				user_capacity.scale_sz = 'MB'
			elif user_capacity.capacity >= 1024: # mayor a 1 KB
				user_capacity.capacity_show = user_capacity.capacity / 1024.0
				user_capacity.scale_sz = 'KB'
			else:
				user_capacity.capacity_show = user_capacity.capacity / 1.0
				user_capacity.scale_sz = 'B'
			user_capacity.save()

			msg = 'Archivo %s subido exitosamente.' % (the_file.name)
	data = {'form':UploadForm(initial={'choices':'privado'}),
			'msg':msg}
	return render(request,'upload_file.html',data)
Example #19
0
def checkfile(request):
    print "called checkfile"
    requestcopy = request.POST.copy()
    form = UploadForm(requestcopy)

    file = request.FILES['trackfile']
    easy = EasyMP3(file)

    form.data['artistname'] = easy['artist'][0]
    form.data['artistdesc'] = 'description'

    form.data['albumname'] = easy['album'][0]
    if 'date' in easy:
        form.data['albumyear'] = easy['date'][0]

    form.data['trackname'] = easy['title'][0]
    form.data['tracknumber'] = easy['tracknumber'][0][0]
    form.data['tracklength'] = int(math.ceil(easy.info.length))

    if 'confirmationbox' in form.data:
        print 'boxfull'
        createdatabaseentries(file, form)
        context = {'uploadform': form}
        return render(request, 'music_streaming/upload.html', context)

    else:
        context = {'uploadform': form}
        return render(request, 'music_streaming/upload.html', context)
Example #20
0
def index(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        #print form.is_valid()
        if form.is_valid():
            return HttpResponseRedirect('/thanks/')
            spreadsheet = request.FILES['spreadsheet']
            print spreadsheet.content_type
    else:
        form = UploadForm()

    return render(request, 'frontpage/index.html', {'form': form})
Example #21
0
def simple_upload(request):
    """
    Handles uploaded files
    """
    try:
        if request.method == 'POST': # If the form has been submitted...
            user =  request.user if request.user.is_authenticated() else None
            form = UploadForm(request.POST, request.FILES) # A form bound to the POST data
            if form.is_valid(): # File was posted with form
                c = None
                kwargs = {}
                kwargs['author'] = user.username.title() if user else 'Anonymous'
                # Create a new Egg
                e = Egg(**kwargs)
                print kwargs
                for filefield, tmpname in handle_uploaded_file(request):
                    print "HANDLING FILE:", filefield, tmpname
                    c = Content(**kwargs)
                    originalname = str(request.FILES["file"])
                    # c.user = request.user # Only authenticated users can use this view
                    c.set_file(originalname, tmpname) # Save uploaded file to filesystem
                    c.get_type_instance() # Create thumbnail if it is supported
                    c.save()
                    e.content = c
                    e.uid = c.uid
                    break # We save only the first file
                if c:
                    c.user = user
                    c.save()
                e.user = user
                print "USER", user
                if user:
                    response_status = 200 # Created
                else:
                    response_status = 401 # Unauthorized
                e.save()
                # We can handle tags after egg has id (it is saved)
                response = HttpResponse(status=response_status)
                #response.status_code = 201
                # FIXME: use reverse()
                #return HttpResponseRedirect(reverse('egg api', args=[e.uid]))
                response['Location'] = '/fourdnest/api/v1/egg/%s/' % e.uid
                return response
            else:
                response = HttpResponse(status=204)
                return response
        else:
            raise Http404
    except Exception, err:
        print err
        raise
        return HttpResponse("Server error", status=500)
Example #22
0
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            image = UploadedImage(name = form.cleaned_data['name'], file = form.cleaned_data['file'])
            image.save()
            return HttpResponseRedirect('/')
    else:
        form = UploadForm()

    return render(request, 'upload.html', {
        'form': form,
    })
Example #23
0
def upload():
    form = UploadForm()

    if request.method == "POST":
        form = UploadForm(request.form)
        if form.validate():
            filename = secure_filename(form.img.file.filename)
            filename.save(os.path.join(UPLOAD_FOLDER, filename))
            flash(ocr(filename))
        else:
            flash("Invalid filename. Please choose another.")

    return render_template("base.html", form=form) 
Example #24
0
def puzzle_upload(request, puzzle_id):
    puzzle = Puzzle.objects.get(id=puzzle_id)
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            handle_puzzle_upload(puzzle, form.cleaned_data['name'], request.FILES['file'])
            return redirect(reverse('puzzles.views.puzzle_info', args=[puzzle_id]))
    else:
        form = UploadForm()
    return render_to_response('puzzles/puzzle-upload.html', puzzle_context(request, {
                'form': form,
                'puzzle': puzzle
                }))
Example #25
0
def experiment(id):
    """实验页面,包含对文件上传的处理"""
    upload_form = UploadForm()
    if upload_form.validate_on_submit():
        """上传并保存文件"""
        f = upload_form.file.data  # 上传的文件

        # 修改了secure_filename源码以支持中文,否则secure_filename()会过滤掉中文,只剩下扩展名
        # 参考:https://blog.csdn.net/qq_30490489/article/details/92000197
        filename = secure_filename(f.filename)  # 文件名

        # 获取本实验上传路径(在本地先建立好uploads/experiment1等4个实验的上传文件夹)
        experiment_name = 'experiment' + str(id)  # 本实验名, eg.'experiment1'
        experiment_path = os.path.join(app.config['UPLOAD_PATH'],
                                       experiment_name)  # 本实验上传路径

        # 若上传路径下已存在该名称的文件,则重命名准备上传的文件
        name, extension = os.path.splitext(filename)
        i = 1
        while os.path.exists(os.path.join(experiment_path, filename)):
            # name, extension = os.path.splitext(filename)
            filename = '%s_%s%s' % (name, str(i), extension)
            i += 1

        # 存储到上传路径
        f.save(os.path.join(experiment_path, filename))  # 存储上传文件

        flash('Upload success.')

        session['filename'] = [filename]

        return redirect(url_for('experiment', id=id))

    if request.method == 'GET':
        """获取并显示本实验路径下的所有文件"""
        # 获取本实验上传路径
        experiment_name = 'experiment' + str(id)  # 本实验名, eg.'experiment1'
        experiment_path = os.path.join(app.config['UPLOAD_PATH'],
                                       experiment_name)

        # 获取文件列表
        files = [
            f for f in os.listdir(experiment_path)
            if os.path.isfile(os.path.join(experiment_path, f))
            and f not in IGNORED_FILES
        ]

    return render_template('experiment.html',
                           experiment=experiments[id - 1],
                           upload_form=upload_form,
                           files=files)
Example #26
0
def dataImport():
    form = UploadForm()
    colnames = get_colnames(Product)
    form.colnames = colnames
    if form.validate_on_submit() and form.filename.data:
        filename = secure_filename(form.filename.data.filename)
        file = request.files[form.filename.name].read()
        open(os.path.join(CSV_PATH, filename), 'w').write(file)
        result = process_csv(os.path.join(CSV_PATH, filename), Product, colnames)
        flash(result)
        redirect('/settings/dataimport')
    return render_template('/settings/dataimport.html',
                           title=gettext("Data Import"),
                           form=form)
Example #27
0
def upload_file_form(game_slug, release_id):
    # release_id = request.args.get('release', None)
    # file_id = request.args.get('file', None)
    # if file_id: # edit/re-upload
        # file = db.session.query(File).filter(File.id==file_id).one()
        # form = UploadForm()
        # form.edit.data = "True"
    # else:
    form = UploadForm()
    form.edit.data = ""
    if form.validate_on_submit():
        uploaded_file = form.uploaded_file.data
        save_file(uploaded_file, release_id)
        flash('File uploaded!')
    return render_template('upload_files.html', form=form, upload_url=game_slug + '/filesupload/'+release_id, site_data=site_data(), navigation=return_navigation())
Example #28
0
def subir(request):
    try:
        if request.method == 'POST':
            form = UploadForm(request.POST, request.FILES)
            if form.is_valid():
                NewPhoto = Fotos(album=request.POST['album'], url=request.FILES['url'])
                NewPhoto.save()
                messages.success(request, 'Imagen subida exitosamente!!! Por favor espere que nuestros administradores la aprueben para que pueda verla publicada')
            else:
                messages.error(request, 'Formato de archivo no aceptado')
        else:
            messages.error(request, 'Error al subir imagen')
    except Exception, e:
        logger.debug(e)
        messages.error(request, 'Error al subir imagen')
Example #29
0
def upload():	
	form = UploadForm()
	if form.validate_on_submit():
		flash('TXT registered')
		db = Db()
		filename = secure_filename(form.upload.data.filename)
		form.upload.data.save(os.path.join(app.config['UPLOADED_TEXT_DEST'], filename))
		SQL =  'INSERT INTO text (author_name, file_location, description, title, text_type, pub_date) VALUES (%s, %s, %s, %s, %s, %s);'
		data = (form.author.data, "uploads/" + form.upload.data.filename, form.description.data, form.title.data, form.textType.data, form.pub_date.data)
		db.execute(SQL, data)
		return redirect(url_for('pick'))

	else:
		filename = None
	return render_template('upload.html', form=form, filename=filename)
Example #30
0
def upload():
		user = g.user
		form = UploadForm()
		if form.validate_on_submit():
				video = Video(link = form.link.data, 
				comment = form.comment.data, 
				timestamp = datetime.datetime.utcnow(),
				author = user)
				db.session.add(video)
				db.session.commit()
				flash("Upload successful!")
				return redirect(url_for('index'))
		return render_template('upload.html',
		title = 'Upload',
		form = form,
		user = user)
Example #31
0
def index(request):
    #add to session starting_from=0
    #return first 5 photos via return_next_posts
    #context = RequestContext(request, )

    #print settings.CONSUMER_KEY
    if request.method  == 'POST':
        #if user is trying to submit new photo
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid() and request.is_ajax() :
            description = form.cleaned_data['description']
            print description
            #think about resizing to a certain size!
            #it has to be a photo (jpg, npg...) not some other
            #file type
            photo = form.cleaned_data['photo']
            #create and save post, but save with status pending !DONE!///
            #Post(description=description, original_photo=photo, ).save()
            logger.info("new photo sent")
            #also return notification regarding the success or failure
            #of post submission
            return HttpResponse(json.dumps({'message':"success"}))#to return clean form
        else:
            #handle badly submitted forms aka
            #someone putted something that isn't a photo
            #when called using ajax it's being recognized as invalid
            #it is required to use FormData as wrapper around form data in html
            #form_object.serialize() works only for form without file fields
            errors =  form.errors
            print errors
            #print "request: ", request
            return HttpResponse(json.dumps({'message':errors}))
    else:
        #if user is first time on the page
        logger.info("came to index page")
        form = UploadForm()
        #get latest Posts (doing that by putting minus sign)
        #negativ index slicing is not allowed while querying in Django
        #take care of case when the number of posts is less then list_end
        #it take cares by it self
        list_end = 3
        posts = Post.objects.filter(status=Post.ACCEPTED).order_by('-pub_date')[:list_end]
        request.session['start_from']=list_end
        #increment start_from at the end

    return render(request, 'photos/index.html', {'form':form, 'posts':posts})
Example #32
0
def upload_file_old(game_slug):
    release_id = request.args.get('release', None)
    file_id = request.args.get('file', None)

    if file_id:
        file = db.session.query(File).filter(File.id==file_id).one()
        form = UploadForm()
        form.edit.data = "True"
    else:
        form = UploadForm()
        form.edit.data = ""

    if form.validate_on_submit():
        uploaded_file = form.uploaded_file.data
        if uploaded_file: # and allowed_file(uploaded_file.filename):
            filename = secure_filename(uploaded_file.filename)
            if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
                fileName, fileExtension = os.path.splitext(filename)
                filename = fileName + '-' + time.strftime("%Y%m%d-%H%M%S") + fileExtension
            uploaded_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        if form.edit.data:
            if uploaded_file:
                file.filename=filename

            file.description=form.description.data
        else:
            if uploaded_file:
#                release = Release.query.filter(Release.id==release_id).one()
                file = File(release_id=release_id, filename=filename, description=form.description.data)
                db.session.add(file)
        if uploaded_file or form.edit.data:
            file.approved = False;
            db.session.commit()
            if not form.edit.data:
                form.description.data=None
        if form.edit.data:
            flash('File changed!')
        else:
            if uploaded_file:
                flash('File uploaded!')
    else:
        if form.edit.data:
            form.description.data=file.description

    return render_template('add_file.html', form=form, site_data=site_data(), navigation=return_navigation())