当前位置: 首页>>代码示例>>Python>>正文


Python forms.UploadFileForm类代码示例

本文整理汇总了Python中forms.UploadFileForm的典型用法代码示例。如果您正苦于以下问题:Python UploadFileForm类的具体用法?Python UploadFileForm怎么用?Python UploadFileForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了UploadFileForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: post

    def post(self, request):
        form = UploadFileForm(request.POST, request.FILES)
        msg = ''

        if form.is_valid():
            test = Test(
                start_time = convert_time(form.cleaned_data['start']),
                end_time = convert_time(form.cleaned_data['end']),
                author_id = UserProfile.objects.get(user__id=request.user.id),
                time = int(form.cleaned_data['time'])
                )
            test.save()
            try:
                test.room = Room.objects.get(id=form.cleaned_data.get('room'))
            except:
                test.room = None
            finally:
                test.save()
            try:
                self.handle_uploaded_file(test.id, request.FILES['file'])
            except:
                test.delete()
                msg = {'error': 'Wystąpił konflikt terminów. Test nie został dodany.'}
                return render(request, self.template_name, {'form': form, 'msg': msg})

            else:
                test.name = self.get_test_name_from_file(test.id)
                test.save()
            return HttpResponseRedirect(reverse('tests'))
        else:
            msg = {'error': u'Wystąpił błąd podczas ładowania pliku.'}
            form = UploadFileForm()
            return render(request, self.template_name, {'form': form, 'msg': msg})
开发者ID:piotut,项目名称:TestSystem,代码行数:33,代码来源:views.py

示例2: home

def home(request):
    form = UploadFileForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.my_save(request)
        return redirect('/')
    else:
        return render(request, "index.html", {"form": form})

# @login_required()
# def userfiles(request):
#     files = DropObjet.objects.filter(user=request.user)
#     #files = DropObjet.objects.all()
#     for file in files:
#         print file.name
#     return render(request, "userfiles.html", {'files': files})
#
# @login_required()
# def show_file(request):
#     name = request.GET.get('name')
#     #name = name.replace('_', ' ')
#     print name
#     print 'Good'
#     file = get_object_or_404(DropObjet, name=name, user=request.user)
#     client = dropbox.client.DropboxClient(settings.AUTH_TOKEN)
#     shared_url = client.share(file.get_path(), short_url=True)
#     print shared_url['url']
#     return render(request, "show_file.html", {'link': shared_url['url']})
开发者ID:anmekin,项目名称:DjBox,代码行数:27,代码来源:views.py

示例3: upload_file

def upload_file(request, pk):
    #获得一个任务的实例
    task_ins = get_object_or_404(Task, pk=pk)

    #如果获取到了POST的提交
    if request.method == 'POST':
        #获取form表单,request.FILES是存放文件的地方
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #通过处理上传文件函数来获得返回值
            uf = handle_uploaded_file(request.FILES['file'])

            #获取上传文件的实例,并补充相应信息至数据库中
            upload_ins = Upload()
            #绑定相应的task id
            upload_ins.task_id = task_ins.id
            #记录相应的文件名
            upload_ins.upload_title = uf[0]
            #记录相应的上传路径
            upload_ins.upload_path = uf[1]
            #保存upload的实例
            upload_ins.save()
            return redirect('task_edit', pk=task_ins.id)
    else:
        form = UploadFileForm()

    #构建相应的context,传递至上传文件页面
    context = {
        'form': form,
        'page_title': '任务处理',
        'sub_title': '上传文件',

    }
    return render(request, 'upload.html', context)
开发者ID:alexchen16,项目名称:echo_site,代码行数:34,代码来源:views.py

示例4: upload_file

def upload_file(request):
    error=None
    if request.method=='POST':
	upload_form=UploadFileForm(request.POST,request.FILES)
	if upload_form.is_valid():
	    client=SaltByLocalApi('/etc/salt/master')
	    target=upload_form.cleaned_data['target']
	    mapping=upload_form.cleaned_data['mapping']
	    upload_path=upload_form.cleaned_data['upload_path']
	    if not is_exist_minion(client,target,mapping) or not request.user.is_superuser:
		error='主机名中存在离线主机,请确认后再上传'
		return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error}))
	    else:
		f=request.FILES.get('upload_file',None)
		if not f:
		    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':'文件损坏'})) 
		tmp_path=os.path.join('/tmp/',f.name)
		with open(tmp_path,'wb+') as tmp_file:
		    for chunk in f.chunks():
			tmp_file.write(chunk)
		if not os.path.exists('/srv/salt/upload'):
		    os.system('mkdir -p /srv/salt/upload')
		cmd="mv {} /srv/salt/upload/".format(tmp_path)
		os.system(cmd)
		file_path=os.path.join(upload_path,f.name)
		bak_file_path=file_path+'.bak'
		bak_cmd='rm -f %s && cp  %s %s' %(bak_file_path,file_path,bak_file_path)
		client.client.cmd(target,'cmd.run',[bak_cmd],expr_form=mapping)
		output=client.client.cmd(target,'cp.get_file',['salt://upload/'+f.name,file_path,'makedirs=True'],expr_form=mapping)
		DistributeFileRecordModel.objects.create(user=request.user.username,hostname=target,pattern=mapping,path=file_path,filename=f.name,opttime=datetime.now())
		return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error,'result':output,'status':200}))
        else:
	    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'cmd_error':'请选择上传的文件!'}))
    upload_form=UploadFileForm()
    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error}))
开发者ID:hujingguang,项目名称:OpsSystem,代码行数:35,代码来源:views.py

示例5: cloud_storage

def cloud_storage(request):

	print '-- cloud_storage:'

	if not request.user.is_authenticated():
		return HttpResponseRedirect("/")

	user = request.user
	profile = userprofile.objects.get(user=request.user)
	secret = profile.secret

	print request.user

	if request.method == 'POST':
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			new_file = Files(file=request.FILES['file'])
			new_file.save()
			Uploaded_Files.objects.create(file=new_file,user=request.user)
  
	uploaded_files = Uploaded_Files.objects.filter(user=request.user).order_by('-pk')
	cloud_storage_menu_open = True

	# XXX batch sync files to the S3.....
	
	return render_to_response('cloud_storage.html', {'cloud_storage_menu_open':cloud_storage_menu_open,'uploaded_files':uploaded_files,'user':user,'profile':profile,}, context_instance=RequestContext(request))
开发者ID:mecirt,项目名称:cloudly,代码行数:26,代码来源:views.py

示例6: api_upload

def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'], user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()  

            response = {'status':'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
开发者ID:PicUpIt,项目名称:picup-it,代码行数:27,代码来源:api_views.py

示例7: upload

def upload(request):
    c = all_page_infos(request)
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            ufile = request.FILES['file']
            short = request.POST['short']
            long_text = request.POST['long_text']
            tags = request.POST['tags']
            (path, written_bytes) = save_uploaded_file(ufile)
            logger.info("User '%s' uploaded file '%s' with title '%s', parsing it now.", request.user, os.path.basename(path), short[:20])
#            try:
            if written_bytes != ufile.size:
                return HttpResponse("Could not store the replay file. Please contact the administrator.")

            demofile = parse_demo_file.Parse_demo_file(path)
            demofile.check_magic()
            demofile.parse()

            try:
                replay = Replay.objects.get(gameID=demofile.header["gameID"])
                logger.info("Replay already existed: pk=%d gameID=%s", replay.pk, replay.gameID)
                return HttpResponse('Uploaded replay already exists: <a href="/replay/%s/">%s</a>'%(replay.gameID, replay.__unicode__()))
            except:
                shutil.move(path, settings.MEDIA_ROOT)
                replay = store_demofile_data(demofile, tags, settings.MEDIA_ROOT+os.path.basename(path), file.name, short, long_text, request.user)
                logger.info("New replay created: pk=%d gameID=%s", replay.pk, replay.gameID)
            return HttpResponseRedirect(replay.get_absolute_url())
#            except Exception, e:
#                return HttpResponse("The was a problem with the upload: %s<br/>Please retry or contact the administrator.<br/><br/><a href="/">Home</a>"%e)
    else:
        form = UploadFileForm()
    c['form'] = form
    return render_to_response('upload.html', c, context_instance=RequestContext(request))
开发者ID:abma,项目名称:spring-replay-site,代码行数:34,代码来源:upload.py

示例8: main

def main(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/',RequestContext(request))

    path = '{}/media/files'.format(os.getcwd())
    file_list = list(os.listdir(path))

    form_1 = UploadFileForm()
    form_2 = UploadDocForm()

    if request.method == 'POST':
        form_1 = UploadFileForm(request.POST, request.FILES)

        if form_1.is_valid():
            new_file = UploadFile(file=request.FILES['file'])
            new_file.save()
            filename = request.FILES['file'].name
            #handle_uploaded_file(request.FILES['file'])
            data = {'name':filename}
            return HttpResponse('Form_1 post file and form is_valid')
    else:
        form_1 = UploadFileForm()


    data = {'form_1': form_1, 'file_list':file_list }
    return render(request,'vedio_parser/vedio_parser_main.html', data)
开发者ID:KentChun33333,项目名称:Django-AE,代码行数:26,代码来源:video_parser_view.py

示例9: UploadExcelForm

def UploadExcelForm(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            wb = xlrd.open_workbook(filename = None,file_contents = request.FILES['excel'].read())
            ws = wb.sheet_by_index(0)
            for r in range(1,ws.nrows):
                megaNo = ws.cell(r,19).value
                sample = models.MedicineSampleInfo.objects.filter(sampleno=megaNo)
                mut_det_res = models.MedicineMutDetRes(id = sample[0].id,chr = ws.cell(r,0).value,start=ws.cell(r,1).value,ref=ws.cell(r,2).value,alt=ws.cell(r,3).value,gene=ws.cell(r,4).value,ref_seq=ws.cell(r,5).value,dna_ch=ws.cell(r,6).value,aa_ch=ws.cell(r,7).value,het=ws.cell(r,8).value,mut_type=ws.cell(r,9).value,disease=ws.cell(r,10).value,result=ws.cell(r,11).value,inher_type=ws.cell(r,12).value,info_gene=ws.cell(r,13).value,info_locus=ws.cell(r,14).value,info_disease=ws.cell(r,15).value,conclusion=ws.cell(r,16).value,ref_paper=ws.cell(r,17).value,ana_type=ws.cell(r,18).value,sam_num=ws.cell(r,19).value)
                mut_det_res.save()
                now = time.strftime('%Y%m%d-%H%M%S', time.localtime())

                try:
                    mut_res_get = models.MedicineMutRes.objects.get(id = sample[0].id)
                except:
                    print "数据库不存在此样本解读结果,执行插入操作"
                    mut_res = models.MedicineMutRes(id=sample[0].id, create_time=now, record_time=now, up_num=1)
                    mut_res.save()
                else:
                    print "数据库已存在此样本解读结果,执行更新操作"
                    up_num = mut_res_get.up_num + 1
                    models.MedicineMutRes.objects.filter(id=sample[0].id).update(record_time=now,up_num=up_num)

            return render_to_response('index/test.html',csrf(request).update({'mut_det_res': mut_det_res}))
    else:
        form = UploadFileForm()
    return render_to_response('index/parsemut.html',csrf(request).update({'from':form,}))
开发者ID:hxoxh,项目名称:yan_han,代码行数:28,代码来源:views.py

示例10: add_avatar

def add_avatar(request):
	#get image from client
	#save image to media folder
	if request.method == "POST":
		logger.debug("[photo]request POST form: "+ str(request.POST))
		form = UploadFileForm(request.POST, request.FILES)
		logger.debug("[photo]request FILES form: "+ str(request.FILES))

		user_name = request.POST.get('username')
		logger.debug("user name: "+user_name)
		if form.is_valid() and form.is_multipart():
			logger.debug("[photo]upload image: "+str(request.FILES))
			save_file(request.FILES['image'])

			# save image path to avatar url
			client_user = User.objects.get(username = user_name)
			client_info = UserInfo.objects.get(user=client_user)
			client_info.avatar.save(request.FILES['image'].name, request.FILES['image'])
			client_info.save()

			return HttpResponse(200)
		else:
			return HttpResponse('invalid image')

	if request.method == "GET":
		return render(request, 'times/photo.html')
开发者ID:youtaya,项目名称:mothertree,代码行数:26,代码来源:views.py

示例11: cloud_storage

def cloud_storage(request):

    print "-- cloud_storage:"

    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    user = request.user
    profile = userprofile.objects.get(user=request.user)
    secret = profile.secret

    print request.user

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = Files(file=request.FILES["file"])
            new_file.save()
            Uploaded_Files.objects.create(file=new_file, user=request.user)

    uploaded_files = Uploaded_Files.objects.filter(user=request.user).order_by("-pk")
    cloud_storage_menu_open = True

    # XXX batch sync files to the S3.....

    return render_to_response(
        "cloud_storage.html",
        {
            "cloud_storage_menu_open": cloud_storage_menu_open,
            "uploaded_files": uploaded_files,
            "user": user,
            "profile": profile,
        },
        context_instance=RequestContext(request),
    )
开发者ID:silvioman,项目名称:cloudly,代码行数:35,代码来源:views.py

示例12: uploader

def uploader(request):
    result = 'Upload failed.'
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            result = handle_uploaded_file(request.FILES['file'])
    return render_to_response('patients/uploader.html', {'result': result})
开发者ID:dimagi,项目名称:arvtracker,代码行数:7,代码来源:views.py

示例13: upload

def upload(request):
    if request.method != 'POST':
        return redirect('index')

    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']
        try:
            name = str(f)
            try:
                isnew = False
                c = Cert.objects.get(filename=name)
            except ObjectDoesNotExist:
                isnew = True
                c = Cert()

            c.frombuffer(f.read())
            if isnew:
                c.filename = name
            c.save()

            return render(request, 'success.html', {
                'vdict': c.verbose_dict(),
                'cert': c,
                'isnew': isnew
            })
        except crypto.Error as e:
            raise e

    return redirect('index')
开发者ID:glebofff,项目名称:djssl,代码行数:30,代码来源:views.py

示例14: upload_customer_report

def upload_customer_report(request):
    result = ""

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if (form.is_valid()):
            upload_file = request.FILES['upload_file']
            filename = upload_file.name
            store_path = os.path.join(config.WORKING_DIR, filename)
            store_file = open(store_path, "wb")

            #upload_file.read()
            for content in upload_file.chunks():
                store_file.write(content)
                #print content[:100]

            store_file.close()
            #result = filename + " is uploaded successfully"
            result = "ok"
        else:
            result = "invalid upload"

        return HttpResponse(result)

    else:
        form = UploadFileForm()
        return render_to_response( "upload_customer_report.html",
                {"upload_customer_report_form":form },
            context_instance=RequestContext(request) )
开发者ID:privateprojects,项目名称:sosproject,代码行数:29,代码来源:views.py

示例15: upload

def upload(request,foobar):
    if not request.user.is_authenticated():
        flag=1
        return render_to_response("notauthorized.html",locals(),context_instance=RequestContext(request))
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():	
            f = form.cleaned_data['files']
            f = request.FILES['files']	
            title = request.POST['title_with_extension']
            if foobar == "img":
                n = len(os.listdir(os.path.join(os.path.dirname(__file__),'..','downloads','gallery').replace('\\','/')))
                x = str(n+1)
                os.system("./manage.py collectstatic ") 
                dest = open(os.path.join(os.path.dirname(__file__),'..','downloads','gallery').replace('\\','/'+'/')+'/'+title,'wb+')
                #return HttpResponse(dest.name)
            elif foobar == "gen":
                n = len(os.listdir(os.path.join(os.path.dirname(__file__),'..','downloads','gen').replace('\\','/')))
                x = str(n+1)
                os.system("./manage.py collectstatic ") 
                dest = open(os.path.join(os.path.dirname(__file__),'..','downloads','gen').replace('\\','/'+'/')+'/'+title,'wb+')
	
            for chunk in request.FILES['files'].chunks():
                dest.write(chunk)
                os.system("./manage.py collectstatic ") 
            dest.close()
            f.close()
            os.system("./manage.py collectstatic ") 
            return HttpResponseRedirect('/corepage/')	
    else:
        form = UploadFileForm()
    return render_to_response('upload.html',{'form': form},context_instance=RequestContext(request))
开发者ID:aravindsankar28,项目名称:Litsoc,代码行数:32,代码来源:views.py


注:本文中的forms.UploadFileForm类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。