示例#1
0
    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})
示例#2
0
文件: views.py 项目: anmekin/DjBox
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']})
示例#3
0
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)
示例#4
0
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}))
示例#5
0
文件: views.py 项目: mecirt/cloudly
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))
示例#6
0
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)
示例#7
0
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))
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)
示例#9
0
文件: views.py 项目: hxoxh/yan_han
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,}))
示例#10
0
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')
示例#11
0
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),
    )
示例#12
0
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})
示例#13
0
文件: views.py 项目: glebofff/djssl
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')
示例#14
0
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) )
示例#15
0
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))
示例#16
0
def publish(request):
    name = lName = request.session.get("name", False)
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        # print form.errors
        if form.is_valid():
            handle_uploaded_file(request)
            title = request.POST.get("title")
            description = request.POST.get("description")
            price = request.POST.get("price")
            category = request.POST.get("category")
            # print request.POST.get('title')
            from datetime import date

            data = Data(
                title=title,
                description=description,
                price=price,
                category=category,
                creator=request.session.get("name"),
                createdDate=date.today(),
            )
            data.save()

            return HttpResponseRedirect("/market/mypublish/")
        else:
            return HttpResponse(form)
    else:
        form = UploadFileForm()
        return render_to_response(
            "dt/publish.html", {"form": form, "lName": lName}, context_instance=RequestContext(request)
        )
示例#17
0
def upload_image_for_match(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #title
            tit = request.REQUEST.get("title", None)
            
            #Sensor
            lon = request.REQUEST.get('longitude', None)
            lat = request.REQUEST.get('latitude', None)
            azi = request.REQUEST.get("azimuth", None)
            pit = request.REQUEST.get("pitch", None)
            rol = request.REQUEST.get("roll", None)
            
            #Image
            image = Image(image_path = request.FILES['file'],
                          azimuth = azi,
                          pitch = pit,
                          roll = rol,
                          longitude = lon,
                          latitude = lat,
                          title = tit)
            image.save()
            
            '''match the image against the database'''
            name = image.match()
            obj = Object.objects.get(object_name = name)
            
            #wrap object_url and object_name as json and return
            return responseJson({'object_url':obj.img_path.name, 'object':obj.object_name})
            
        else:
            return fail()
    else:
        return fail()
示例#18
0
文件: utils.py 项目: mpevner/djKarma
def uploadForm(user):
    """ Creates an UploadFileForm and pre-populates the school field
        With the user's school, if available
        is currently unused?
    """
    #print request.user.username
    user_profile = user.get_profile()
    if user_profile.school:
        print "The user has a school, so we will auto populate it"
        # This isn't the ideal way to override the field system. I would rather extend or replicate the existing UploadFileForm, but I am slightly unsure how to do that
        # Alternatively, I could figure out how to use the 'school' kv argument
        form = UploadFileForm(initial={'course': -1, 'school': user_profile.school.pk})
        form.fields['school'] = djangoforms.ModelChoiceField(
                queryset=School.objects.all(),
                widget=AutoCompleteWidget(
                    url='/schools',
                    initial_display=user_profile.school.name
                ),
                error_messages={'invalid_choice': 'Enter a valid school. Begin typing a school name to see available choices.',
                                'required': 'Enter a school.'},
            )
    else:
        # Provide bogus default school and course data to ensure
        # legitimate data is chosen
        form = UploadFileForm(initial={'course': -1, 'school': -1})
    return form
示例#19
0
def file_share(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            result = handle_uploaded_file(request.FILES['file'])
            if result:
                try:
                    file = File.objects.get(sha512=result['sha512'], user=request.user)
                    messages.error(request, 'You have already reported this file')
                    return HttpResponseRedirect('/file/%s' % file.id)
                except ObjectDoesNotExist:
                    file = form.save(commit=False)
                    file.uuid = uuid.uuid4().urn
                    file.user = request.user
                    file.filename = result['filename']
                    file.filesize = result['filesize']
                    file.md5 = result['md5']
                    file.sha1 = result['sha1']
                    file.sha256 = result['sha256']
                    file.sha512 = result['sha512']
                    file.save()
                    form.save_m2m()
                    for n in request.POST.getlist('nodes'):
                        node = PubSubNode.objects.get(node=int(n))
                        file.nodes.add(node)
                        xmpp.publish(node=node.node, payload=file.activity_fordrop_file())
                        if file.tags.all():
                            xmpp.publish(node.node, payload=file.activity_tags())

                    print json.dumps(file.activity_fordrop_file(), indent=4)
                    messages.success(request, "Sharing is caring, file successfully recieved!")
                    mail_body = '%s reported the same file as you, %s\n%s' % (file.user.profile.name, file.sha1, file.get_full_uri())
                    notify_by_mail(users=file.get_reporters(), subject='%s reported the same file as you' % file.user.profile.name, body=mail_body, obj=file)
    return HttpResponseRedirect('/file/%s' % file.id)
示例#20
0
文件: views.py 项目: meeeejin/MONITT
def create_test(request):
    username = auth_check(request)

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            testfile = request.FILES["testfile"]
            new_file = UploadFile(testfile=request.FILES["testfile"])
            new_file.save()
            command = (
                "/usr/bin/python "
                + test_path
                + "/dashboard/testsrc/main.py "
                + test_path
                + "/../static/media/files/"
                + testfile.name
            )
            os.system(command)
            return HttpResponseRedirect(reverse("dashboard.views.create_test"))
    else:
        form = UploadFileForm()

    data = {"form": form}

    return render_to_response("create_test.html", locals(), context_instance=RequestContext(request))
示例#21
0
文件: views.py 项目: traceur/lbplayer
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            dest = form.cleaned_data['dest']
            handle_uploaded_file(dest, request.FILES['file'])
    return redirect('/')
示例#22
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'], request.user)
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('filetest.html', {'form': form})
示例#23
0
文件: view.py 项目: zhougit86/mysite
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            Raw_Input.handle_upload_file(request.FILES['file'])
            return HttpResponseRedirect('show')
    else:
        form=UploadFileForm()
    return render_to_response('upload.html',{'form': form},context_instance=RequestContext(request))
示例#24
0
def upload(request):

    if request.method == 'POST':
        upload_form = UploadFileForm(request.POST, request.FILES)
        if upload_form.is_valid():
            upload_form.handle_files()


    return HttpResponse('ok')
示例#25
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'],request.user)
            return HttpResponseRedirect(reverse("deck:deck_list") )
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', RequestContext(request,{'form': form}))
示例#26
0
def upload(request):
	#if request.method == 'POST':
	form = UploadFileForm(request.POST, request.FILES)
	if form.is_valid() and request.user.is_authenticated:
		codefile = request.FILES['file']
		data = codefile.read().splitlines()
		index = 0
		error = 0
		if request.POST['type'] == '1':
			parent = ''
			for code in data:
				if code != 'NEWPARENT':
					try:
						b = Barcode.objects.get(code=code.upper())
						if parent == '':
							p = Barcode.objects.get(code=code.upper())
							parent = code
						else:
							i = Barcode.objects.get(code=code.upper())
							i.item.parent = p.item
							i.item.save()
					except ObjectDoesNotExist:
						error += 1
						data[index] = code + ' existiert nicht!'
				else:
					parent = ''
				index += 1
		elif request.POST['type'] == '2':
			business_area = models.BusinessArea.objects.get(name='ideell')
			category = models.Category.objects.get(name='Inventar')
			parent = models.Barcode.objects.get(code='H0000')
			tag = models.Tag.objects.get(name='Regale & Storage')

			for code in data:
				if code[0] == 'H' and len(code) == 5:
					try:
						b = Barcode.objects.get(code=code.upper())
						error += 1
						data[index] = code + ' existiert bereits'
					except ObjectDoesNotExist:
						name = 'Regalborte ' + code
						description = 'Borte im Hochregal \nReihe: ' + code[1] + '\nRegal: ' + code[2]
						i = models.Item(name=name, description=description, business_area=business_area, category=category, parent=parent.item, inUse=True)
						i.save()
						i.tag.add(tag)
						i.save()
						barcode = Barcode(code=code, item=i)
						barcode.save()
				else:
					data[index] = code + ' ist nicht im richtigen Format'
					error += 1
				index += 1
		return render(request, 'upload.html', {'form': form, 'data': data})
	else:
		form = UploadFileForm()
	return render(request, 'upload.html', {'form': form})
示例#27
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            fileName = handle_uploaded_file(request.FILES['file'])
            
            return HttpResponse('You file has been uploaded to %s ' % fileName)
    else:
        form = UploadFileForm()
    return render_to_response('testing/upload.html', {'form': form})
示例#28
0
def uploader(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
    else:
        form = UploadFileForm()
    context = {'form': form}
    return render(request, 'uploader.html', context)
示例#29
0
def prueba(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Usuario(us_img = request.FILES['file'])
            newdoc.save(form)
            return HttpResponseRedirect('/appella/')
    else:
        form = UploadFileForm()
    return render(request, 'index.html', {'form': form})
示例#30
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect(
                'success/'
            )
    else:
        form = UploadFileForm()
    return render(request, 'plink/upload.html', {'form': form})