def upload(request): name = "" if request.method == 'POST' and request.POST.get('search', "") == "": context = {} form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newDoc = Document(docfile=request.FILES.get('docfile', "")) name = form.cleaned_data['docfile'].name newDoc.save() documents = Document.objects.all() if name != "": location = "../media/uploads/" + name s = convert_video_to_frame(cwd + "/media/uploads/" + name) sorted_inverted = model_to_inverted_index(s) print sorted_inverted convert_from_mili(sorted_inverted) val = 1 if len(Index.objects.filter()) > 0: val = len(Index.objects.filter()) + 1 b = Index(invertedIndex=json.dumps(sorted_inverted), name=name, video_id=val, images=json.dumps(s)) vid_id = b.video_id b.save() return redirect("/video/%s" % vid_id) return render(request, 'home.html', context) if request.method == 'GET': return render(request, 'upload.html')
def cargar_mod(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #print(newdoc.docfile.name) manejo_mods.insmod('/home/pi/SO2TP3PerezFederico/PaginaTP3/media/'+newdoc.docfile.name) archivo = open('salida.txt','r') lista = [] for linea in archivo: lista.append(linea) return render_to_response( 'list.html', {'documents': lista}, context_instance=RequestContext(request)) # Redirect to the document list after POST # return HttpResponseRedirect(reverse('cargar_mod')) else: form = DocumentForm() # A empty, unbound form # Render list page with the documents and the form return render_to_response( 'list.html', {'form': form}, context_instance=RequestContext(request) )
def uploadAFile(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) some_file = File(request.FILES['docfile']) # import pdb # pdb.set_trace() # print averageMinuteFileContent if form.is_valid(): path = default_storage.save('averaging.txt', ContentFile(some_file.read())) averageFileName = averaging(path, some_file.name) averageMinuteFile = averageFileName + '_minute.csv' averageHourFile = averageFileName + '_hour.csv' averageDailyFile = averageFileName + '_daily.csv' fileHandlerMinute = open(averageMinuteFile, 'rb') fileHandlerHour = open(averageHourFile, 'rb') fileHandlerDay = open(averageDailyFile, 'rb') averageMinuteFileHandle = File(fileHandlerMinute) averageHourFileHandle = File(fileHandlerHour) averageDayFileHandle = File(fileHandlerDay) # print averageMinuteFileHandle.__dict__ # print some_file.__dict__ newdoc = Document( podId=request.POST['podId'], location=request.POST['location'], startDate=request.POST['startDate'], endDate=request.POST['endDate'], podUseType=request.POST['podUseType'], pollutantOfInterest=request.POST['pollutantOfInterest'], podUseReason=request.POST['podUseReason'], projectName=request.POST['projectName'], mentorName=request.POST['mentorName'], school=request.POST['school'], userName=request.user.first_name, docfile=some_file, averageMinuteFile=averageMinuteFileHandle, averageHourFile=averageHourFileHandle, averageDayFile=averageDayFileHandle # averageMinuteFile=averageMinuteFileHandle ) # print request.FILES['docfile'] newdoc.save() os.remove(averageMinuteFile) os.remove(averageHourFile) os.remove(averageDailyFile) # Redirect to the document list after POST return HttpResponseRedirect(reverse('uploadedFiles')) else: form = DocumentForm() # A empty, unbound form # Render list page with the documents and the form return render(request, 'upload.html', {'form': form})
def import_file(request): models = [ 'inventory.inventory', 'inventory.inventorytransaction', 'assets.itemgroup', 'assets.itemstate', 'inventory.itemtemplate', 'inventory.location', 'assets.person', 'assets.state', 'inventory.supplier', 'assets.item', ] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES, models=models) if form.is_valid(): temp_file = handle_uploaded_file(form.cleaned_data['local_document']) return HttpResponseRedirect( '?'.join( [reverse('import_next_steps'), urlencode({ 'temp_file':temp_file, 'model_name':form.cleaned_data['model_name'], })])) else: form = DocumentForm(models=models) return render_to_response('generic_form.html', { 'form':form, 'title':_(u'Upload a file to import'), }, context_instance=RequestContext(request))
def executeUpload(request): # Save the files form = DocumentForm(request.POST, request.FILES) file_new = request.FILES['docfile'] if form.is_valid(): #Save temporary file newdoc = Document(docfile=file_new) newdoc.save() fn = file_new.name fn = fn.replace(" ", "_") #Move the file to the new folder src = os.path.join(django_settings.FILE_UPLOAD_TEMP_DIR, 'uploads', fn) file_upload = src path = os.path.join(request.session['projectPath'], 'Uploads') target = os.path.join(path, fn) if os.path.exists(target): os.remove(target) shutil.move(src, path) #Delete the temporary file newdoc.delete()
def index(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() question = form.cleaned_data['question'] renderthis = process(newdoc.docfile.name, question) imageurlcontainer = renderthis[0] anstemp = renderthis[1] anstemp = anstemp.split("\n") print anstemp ans = anstemp[-2].strip() return render( request, 'polls/showimg.html', { "imageurlcontainer": imageurlcontainer, "ans": ans, "question": question }) else: return HttpResponse("Error brah") else: system("pwd") form = DocumentForm() documents = Document.objects.all() return render(request, 'polls/index.html', {"form": form})
def import_file(request): models = [ 'inventory.inventory', 'inventory.inventorytransaction', 'assets.itemgroup', 'assets.itemstate', 'inventory.itemtemplate', 'inventory.location', 'assets.person', 'assets.state', 'inventory.supplier', 'assets.item', ] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES, models=models) if form.is_valid(): temp_file = handle_uploaded_file( form.cleaned_data['local_document']) return HttpResponseRedirect('?'.join([ reverse('import_next_steps'), urlencode({ 'temp_file': temp_file, 'model_name': form.cleaned_data['model_name'], }) ])) else: form = DocumentForm(models=models) return render_to_response('generic_form.html', { 'form': form, 'title': _(u'Upload a file to import'), }, context_instance=RequestContext(request))
def investing(request): # Handle file upload file_form = FileForm(request.POST) form = DocumentForm(request.POST, request.FILES) if request.method == 'POST' and "uploadFile" in request.POST: # Upload if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('dataloader.views.investing')) elif request.method == 'POST' and "invest" in request.POST: # Make Investments if file_form.is_valid(): file_name = file_form.cleaned_data['file_input'] print "### FILE FOR INVESTMENTS: " + file_name file_path = settings.MEDIA_ROOT + "/" + file_name print file_path cr = csv.reader(open(file_path)) # Starting from second row for row in cr: if row[0] == 'fund' or row[0] == 'individual': investment_manager.fund(row) elif row[0] == 'buy': investment_manager.buy(row) elif row[0] == 'sell': investment_manager.sell(row) elif row[0] == 'sellbuy': investment_manager.sellbuy(row) return HttpResponseRedirect(reverse('dataloader.views.investing')) elif request.method == 'POST' and "clear" in request.POST: # Clear Investments print "### This should clear everything" Activity.objects.all().delete() StakeHold.objects.all().delete() Port_Indi.objects.all().delete() print "### OK check porfolio page" else: form = DocumentForm() # A empty, unbound form file_form = FileForm() # Load documents for the list page documents = Document.objects.all() return render_to_response( 'nav/investing.html', {'documents': documents, 'form': form, 'file_form':file_form}, context_instance=RequestContext(request) )
def edit_document(request, id=None): """Edit a document""" ctx = copy.copy(default_ctx) if id is None: doc = None cur_revision = 0 else: doc = get_object_or_404(Document, id=id) if request.user != doc.owner and not doc.contributors.filter(id=request.user.id).exists(): raise Http404 cur_revision = doc.revision if request.method == 'POST': # giving doc to the form may change its contents, so copy them now if doc is not None: cur_content = doc.content form = DocumentForm(request.POST, instance=doc) if form.is_valid(): if cur_revision == form.cleaned_data['revision']: new_doc = form.save(commit=False) # update revision new_doc.revision = cur_revision + 1 if doc is None: # owner is not set when creating a new document new_doc.owner = request.user new_doc.save() return redirect('show_document', new_doc.id) else: # document was changed during editing ctx['diff_warning'] = True ctx['cur_content'] = cur_content ctx['diff'] = ''.join(difflib.ndiff(doc.content.splitlines(1), cur_content.splitlines(1))) form = DocumentForm(instance=doc, initial={'revision': cur_revision }) ctx['doc'] = doc ctx['form'] = form return render_to_response('edit_document.html', ctx, RequestContext(request))
def web_import_xml(request): """ redirects to login page if user is not logged in otherwise, renders page with import functionality if called with POST request... check imported data against schema using minixsv puts data into database if validation succeeds """ if request.user.is_authenticated(): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): imported_file = request.FILES['docfile'].read() f_import = open('importXML.xml', 'w') f_import.write(imported_file) f_import.close() try: bo = check_imported_file(imported_file) except Exception: bo = False if bo: import_xml(imported_file) return render_to_response('importing.html', {'import_status': 'Import succeeded.'}) else: return render_to_response('importing.html', {'import_status': 'Import failed.'}) else: form = DocumentForm() return render_to_response('import.html', {'form': form}, context_instance=RequestContext(request)) else: return render_to_response('login.html', context_instance=RequestContext(request))
def executeUpload(request): # Save the files form = DocumentForm(request.POST, request.FILES) file_new = request.FILES['docfile'] if form.is_valid(): #Save temporary file newdoc = Document(docfile = file_new) newdoc.save() fn = file_new.name fn = fn.replace (" ", "_") #Move the file to the new folder src = os.path.join(django_settings.FILE_UPLOAD_TEMP_DIR, 'uploads', fn) file_upload = src path = os.path.join(request.session['projectPath'],'Uploads') target = os.path.join(path, fn) if os.path.exists(target): os.remove(target) shutil.move(src, path) #Delete the temporary file newdoc.delete()
def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(pk=1) f = request.FILES['docfile'] newdoc.docfile = f newdoc.name = f.name newdoc.save() # Redirect to the document list after POST #return HttpResponseRedirect(reverse('myproject.myapp.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page try: document = Document.objects.get(pk=1) except Document.DoesNotExist: document = None #update game if gameHeart: gameHeart.restart() # Render list page with the documents and the form return render_to_response( 'list.html', {'document': document, 'form': form}, context_instance=RequestContext(request) )
def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Advertisment(docfile = request.FILES['docfile'], Add_title = request.POST['Add_title'], Add_brand = request.POST['Add_brand'], Add_about = request.POST['Add_about'], Add_entry_dt = request.POST['Add_entry_dt'],) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect('/adds/list/') else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Advertisment.objects.all() # Render list page with the documents and the form return render(request, "list.html",{'documents':documents,'form':form}) ####for file field # def list(request): # # Handle file upload # if request.method == 'POST': # form = DocumentForm(request.POST, request.FILES) # if form.is_valid(): # newdoc = Document(docfile = request.FILES['docfile']) # newdoc.save() # # Redirect to the document list after POST # return HttpResponseRedirect('/adds/list/') # else: # form = DocumentForm() # A empty, unbound form # # Load documents for the list page # documents = Document.objects.all() # # Render list page with the documents and the form # return render(request, "list.html",{'documents':documents,'form':form}) # def index(request): # return render_to_response('myapp/index.html')
def upload_image(request): if request.method == 'POST': form = DocumentForm(data=request.POST, files=request.FILES) if form.is_valid(): print 'valid form' username = request.session['username'] current_user = UserInfor.objects.get(username=username) parts = str(request.FILES['docfile']).split('.') if len(parts) != 2: data = { 'result': 'fail', 'message': 'The image shall not contain many dots' } else: name = parts[0] exts = parts[1] if exts.lower() not in ['jpg', 'jpeg', 'png', 'gif']: data = { 'result': 'fail', 'message': 'Must select an image file extension' } else: current_user.docfile = request.FILES['docfile'] current_user.save() request.session['uploaded_photo'] = str( request.FILES['docfile']) data = { 'result': 'success', 'message': 'Successfully upload image', 'uploaded_file': str(request.FILES['docfile']) } return HttpResponse(json.dumps(data)) else: form = DocumentForm() # A empty, unbound form return render(request, 'mygallery.html', {'form': form})
def edi_translator(request): form = DocumentForm(request.POST, request.FILES) if form.is_valid(): new_file = models.edi_address(edi_file = request.FILES['docfile']) new_file.save() print new_file.id return HttpResponseRedirect(('{}').format(new_file.id)) return render(request, 'EDI/traducir.html', {'form': form})
def upload_document_with_type(request, document_type_id, multiple=True): check_permissions(request.user, "documents", [PERMISSION_DOCUMENT_CREATE]) document_type = get_object_or_404(DocumentType, pk=document_type_id) local_form = DocumentForm(prefix="local", initial={"document_type": document_type}) if USE_STAGING_DIRECTORY: staging_form = StagingDocumentForm(prefix="staging", initial={"document_type": document_type}) if request.method == "POST": if "local-submit" in request.POST.keys(): local_form = DocumentForm( request.POST, request.FILES, prefix="local", initial={"document_type": document_type} ) if local_form.is_valid(): try: if (not UNCOMPRESS_COMPRESSED_LOCAL_FILES) or ( UNCOMPRESS_COMPRESSED_LOCAL_FILES and not _handle_zip_file(request, request.FILES["local-file"], document_type) ): instance = local_form.save() _handle_save_document(request, instance, local_form) messages.success(request, _(u"Document uploaded successfully.")) except Exception, e: messages.error(request, e) if multiple: return HttpResponseRedirect(request.get_full_path()) else: return HttpResponseRedirect(reverse("document_list")) elif "staging-submit" in request.POST.keys() and USE_STAGING_DIRECTORY: staging_form = StagingDocumentForm( request.POST, request.FILES, prefix="staging", initial={"document_type": document_type} ) if staging_form.is_valid(): try: staging_file = StagingFile.get(staging_form.cleaned_data["staging_file_id"]) if (not UNCOMPRESS_COMPRESSED_STAGING_FILES) or ( UNCOMPRESS_COMPRESSED_STAGING_FILES and not _handle_zip_file(request, staging_file.upload(), document_type) ): document = Document(file=staging_file.upload(), document_type=document_type) document.save() _handle_save_document(request, document, staging_form) messages.success( request, _(u"Staging file: %s, uploaded successfully.") % staging_file.filename ) if DELETE_STAGING_FILE_AFTER_UPLOAD: staging_file.delete() messages.success(request, _(u"Staging file: %s, deleted successfully.") % staging_file.filename) except Exception, e: messages.error(request, e) if multiple: return HttpResponseRedirect(request.META["HTTP_REFERER"]) else: return HttpResponseRedirect(reverse("document_list"))
def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): return upload_video(request) else: form = DocumentForm() return render(request, 'upload/model_form_upload.html', {'form': form})
def upload_file(request): documents = Document.objects.all() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(name = request.POST['name'], label = request.POST['label'], docfile = request.FILES['docfile']) newdoc.save() return redirect('/docs') else: form = DocumentForm() documents = Document.objects.all() return render(request, 'network/docs.html', {'documents': documents, 'form': form})
def create_document(request): """View for creating new documents""" if request.method == 'POST': form = DocumentForm(request.POST) if form.is_valid(): d = form.save(commit=False) d.owner = request.user d.save() return redirect('show_document', d.id) else: form = DocumentForm() ctx = copy.copy(default_ctx) ctx['form'] = form return render_to_response('create_document.html', ctx, RequestContext(request))
def expuploads(request): # Handle file uploads if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES, request.POST.get('dirName', 'error')) # redirect to the document after POST return HttpResponseRedirect(reverse('uploads.views.expuploads')) else: form = DocumentForm() # An empty, unbound form experiments = Experiment.objects.all() # Render list page with the documents and the form return render(request, 'expuploads.html', {'form': form, 'experiments': experiments})
def detail(request, apikey, pk): form = DocumentForm() documents = Document.objects.filter(pk=pk) return render(request, 'detail.html', { 'documents': documents, 'form': form })
def delete(request, apikey, pk): form = DocumentForm() document = get_object_or_404(Document, pk=pk) if os.path.exists(os.path.join(MEDIA_ROOT, document.image.name)): os.remove(os.path.join(MEDIA_ROOT, document.image.name)) document.delete() return redirect('list_all', apikey=apikey)
def doUpload(request): form = DocumentForm(request.POST, request.FILES) try: executeUpload(request) except Exception, ex: print "Error: %s" % ex return HttpResponse("error", mimetype='application/javascript')
def translations(request, project_id, language_id): ctx = RequestContext(request, {}) project = Project.objects.get(id=project_id) language = Language.objects.get(id=language_id) total_languages = Language.objects.filter(project=project) if request.method == 'POST': selected_language = Language.objects.get(id=request.POST['language']) form = DocumentForm(request.POST, request.FILES) if form.is_valid(): input_file = request.FILES['docfile'] persist_uploaded_file(project, selected_language, request.POST['platform'], input_file) return render_to_response('translations/index.html', {'project': project, 'language': language, 'form': form}, context_instance=ctx) else: form = DocumentForm() return render_to_response('translations/index.html', {'project': project, 'language': language, "languages": total_languages, 'form': form}, context_instance=ctx)
def list_documents(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #try: parse_excel(newdoc) #except: #print "FXCK" # Redirect to the document list after POST return HttpResponseRedirect( reverse('exceltoldap.views.list_documents')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list_documents page try: documents = Document.objects.all() last_document = Document.objects.latest('uploaded') except: last_document = None # Render list_documents page with the documents and the form places = EpicPlace.objects.all() vehicles = EpicVehicle.objects.all() users = EpicUser.objects.all() dev_places = EpicDevice.objects.exclude(place=None) dev_vehicles = EpicDevice.objects.exclude(vehicle=None) dev_users = EpicDevice.objects.exclude(owner=None) devices = EpicDevice.objects.all() mission = last_document.missionName return render_to_response('list_documents.html', { 'documents': documents, 'last_document': last_document, 'form': form, 'places': places, 'vehicles': vehicles, 'users': users, 'devices_places': dev_places, 'devices_vehicles': dev_vehicles, 'devices_users': dev_users, 'devices': devices }, context_instance=RequestContext(request))
def upload(request): form = DocumentForm() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data api_key = data['apikey'] if not os.path.exists(os.path.join(MEDIA_ROOT, api_key)): return HttpResponse("Invalid api key.") doc = request.FILES['image'] from django.core.exceptions import ValidationError if not doc.content_type.startswith('image'): return HttpResponse('Unsupported file extension.') newdoc = Document(path=api_key, image=doc) newdoc.save() return redirect(reverse('upload')) return render(request, 'upload.html', {'form': form})
def get_predicted_tag(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() file_name = str(request.FILES['docfile'].name) file_name = file_name.replace(" ", "_") file_path = settings.MEDIA_ROOT + "/documents/" + file_name file_url = settings.MEDIA_URL + "/documents/" + file_name img_actual = Image.open(file_path) img_actual = img_actual.convert("L") img_actual = img_actual.resize((50, 50), Image.ANTIALIAS) predict_tag = get_prediction(list(img_actual.getdata())) # img_actual.save(file_path, quality=95) http_response = HttpResponse() response = { 'image_path': file_path, 'image_url': file_url } prediction_result = { 'predicted': predict_tag } http_response = render( request, '../templates/image_quality_tagging/display_prediction.html', {"image_data": response, "prediction_result": prediction_result}) if not request.COOKIES.get('uid'): value = encrypt( str(request.COOKIES.get('csrftoken')) + str(request.META.get('HTTP_USER_AGENT'))) http_response.set_cookie(key='uid', value=value) return http_response else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render_to_response( '../templates/image_quality_tagging/index.html', context_instance=RequestContext(request) )
def add_document(request): """ Add a document """ label_options = {'labels': {'item_type': 'Document type'}} dform = DocumentForm(user=request.user) # rform = ReferenceForm() tag_formset = get_tag_formset(**label_options) if request.method == 'POST': # rform = ReferenceForm(request.POST) dform = DocumentForm(request.POST, request.FILES, user=request.user) tag_formset = get_tag_formset(dform.instance, data=request.POST, **label_options) #this avoids ignoring the evaluation of the form to show the errors # rf_is_valid = rform.is_valid() rf_is_valid = True df_is_valid = dform.is_valid() if rf_is_valid and df_is_valid and tag_formset.is_valid(): # rform.save() # dform.instance.reference = rform.instance dform.save() # file = dform.cleaned_data['file'] # dform.instance.seet_file(file=file, filename=file.name) assign_perm('documents.access_document', request.user, dform.instance) tag_formset.save() return HttpResponseRedirect(reverse('documents.views.list_documents')) return render_to_response('add_document.html', { 'dform': dform, 'rform': None, 'formset': tag_formset, }, context_instance=RequestContext(request))
def draft_new(request, template_name='doccomment/doc_editor.html'): if request.method == 'POST': form = DocumentForm(request.POST) if form.is_valid(): doc = form.save(commit=False) doc.author = request.user doc.save() if request.POST.get('save-and-continue', None): url = reverse('doccomment_draft_edit', kwargs={'id':doc.id}) else: url = reverse('doccomment_draft_list') # TODO: use django-messages to display "saved" message return HttpResponseRedirect(url) else: form = DocumentForm() return render_to_response(template_name, { 'form' : form, }, context_instance=RequestContext(request))
def list(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() documents = Document.objects.all() return render_to_response( 'uploader/list.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request) )
def create_document_in_collection(request, database_name=settings.MONGO_DB_NAME, collection_name=settings.MONGO_MASTER_COLLECTION): name = _("Create a Document from JSON") if request.method == 'POST': form = DocumentForm(request.POST) if form.is_valid(): document = form.cleaned_data['document'] #create the document results = mongo_create_json_util(document, database_name=database_name, collection_name=collection_name) #convert to json and respond. results_json = json.dumps(results, indent = 4) return HttpResponse(results_json, status=int(results['code']), mimetype="application/json") else: #The form is invalid messages.error(request,_("Please correct the errors in the form.")) return render_to_response('generic/bootstrapform.html', {'form': form, 'name':name, }, RequestContext(request)) #this is a GET if not database_name or collection_name: idata ={'database_name': settings.MONGO_DB_NAME, 'collection_name': settings.MONGO_MASTER_COLLECTION, } else: idata ={'database_name': database_name, 'collection_name': collection_name, } context= {'name':name, 'form': DocumentForm(initial=idata) } return render_to_response('generic/bootstrapform.html', RequestContext(request, context,))
def carregando_arquivo_teste_passo_1(request): if request.method == 'POST': lamina=request.POST['select'] lamina=int(lamina) criterio=request.POST['criterio'] criterio=int(criterio) angulo=float(request.POST['angulo_inicial']) form = DocumentForm(request.POST, request.FILES) if form.is_valid(): docfile=request.FILES['docfile'] newdoc = Document(docfile=request.FILES['docfile']) entrada_Esforcos=[] module_dir = os.path.dirname(__file__) file_path = os.path.join(module_dir, 'temporal.csv') temporal=open(file_path,"w") for chunk in docfile.chunks(): temporal.write(chunk) temporal.close() color_fundo="background-color:LightPink;" # /criterios_envelopes_julian/area_programador/funcao/carregando_arquivo_teste_passo_1 return HttpResponseRedirect( '/criterios_envelopes_julian/area_programador/carregando_arquivo_teste_passo_2/%d/%f/%d/' % (lamina,angulo,criterio)) else: documents = Document.objects.all() color_fundo="background-color:LightPink;" c={'documents': documents, 'form': form, 'color_fundo':color_fundo, } return render(request,'area_programador/list.html',c) else: form = DocumentForm() # A empty, unbound form # END IF (REQUEST METHOD) documents = Document.objects.all() color_fundo="background-color:Tan;" c={'documents': documents, 'form': form, 'color_fundo':color_fundo, } return render(request,'area_programador/list.html',c)
def index(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(request.META['HTTP_REFERER']) else: form = DocumentForm() # A empty, unbound form documents = Document.objects.all() template = loader.get_template('prediction/index.html') return render(request, 'prediction/index.html', { 'documents': documents, 'form': form })
def upload_file(request): #render the upload file page and handle file uploads if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): #read file in and name of collection data = request.FILES['docfile'].read() newdoc = Bibcollection(bibfile = request.FILES['docfile']) newdoc.name = request.POST['name'] newdoc.save() newdoc = Bibcollection.objects.get(pk= newdoc.id) parser = bibtex.Parser() #write uploaded .bib to a temporary file f = open('temp.bib','w') f.write(data) f.close() result = parser.parse_file('temp.bib') #add entries to the collection for entry in result.entries.keys(): item = result.entries[entry] title = parseitem(item,'title') author = parseitem(item,'author') volume = parseitem(item,'volume') pages = parseitem(item,'pages') year = parseitem(item,'year') journal = parseitem(item,'journal') tag = entry itemtype = result.entries[entry].type newdoc.article_set.create(itemtype = itemtype, title = title, author = author, volume = volume, pages = pages, year = year, tag = tag, journal = journal,collection_name=newdoc.name) else: # instantiate an empty form form = DocumentForm() #build a database if one doesnt exist try: dblen = len(Bibcollection.objects.all()) except: call_command('syncdb',interactive=False) #render the page return render_to_response('upload.html', {'form':form}, context_instance=RequestContext(request))
def list_my_files(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('neal_main:list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render(request, 'neal_main/list.html', {'documents': documents, 'form': form}) """
def create_doc(request): if request.method == 'POST': doc = Document() form = DocumentForm(request.POST, request.FILES, instance=doc) if (form.is_valid()): form.save() return redirect(reverse('documents:index')) else: form = DocumentForm(request.POST, request.FILES, instance=doc) else: form = DocumentForm() context = { 'form': form, 'form_url': reverse('documents:create_doc'), } return render(request, 'documents/edit_doc.html', context)
def index(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() greyscale = form.cleaned_data['greyscale'] smoothen = form.cleaned_data['smoothen'] binarythreshold = form.cleaned_data['binarythreshold'] resize = form.cleaned_data['resize'] histogram = form.cleaned_data['histogram'] edgedetection = form.cleaned_data['edgedetection'] sobelfilter = form.cleaned_data['sobelfilter'] foregroundextract = form.cleaned_data['foregroundextract'] stufftodo = [] if (greyscale == True): stufftodo.append("greyscale") if (smoothen == True): stufftodo.append("smoothen") if (binarythreshold == True): stufftodo.append("binarythreshold") if (resize == True): stufftodo.append("resize") if (histogram == True): stufftodo.append("histogram") if (edgedetection == True): stufftodo.append("edgedetection") if (sobelfilter == True): stufftodo.append("sobelfilter") if (foregroundextract == True): stufftodo.append("foregroundextract") imageurlcontainer = process(request, newdoc.docfile.name, stufftodo) return render(request, 'polls/showimg.html', {"imageurlcontainer": imageurlcontainer}) else: return HttpResponse("Error brah") else: form = DocumentForm() documents = Document.objects.all() return render(request, 'polls/index.html', {"form": form})
def neal_index(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('neal_main:neal_index')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() list1 = [] list1 = get_start_end_times() # Render list page with the documents and the form return render(request, 'neal_main/index.html', {'form': form, 'list1':list1})
def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile'],owner=request.user) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('incentive.views.list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents=None if request.user.is_active: documents = Document.objects.filter(owner=request.user) # Render list page with the documents and the form return render_to_response('list.html', locals(), context_instance=RequestContext(request) )
def document_edit(request, document_id, response_format='html'): "Document edit page" document = get_object_or_404(Document, pk=document_id) if not request.user.profile.has_permission(document, mode='w'): return user_denied(request, message="You don't have access to this Document") if request.POST: if 'cancel' not in request.POST: form = DocumentForm( request.user.profile, None, request.POST, instance=document) if form.is_valid(): document = form.save() return HttpResponseRedirect(reverse('documents_document_view', args=[document.id])) else: return HttpResponseRedirect(reverse('documents_document_view', args=[document.id])) else: form = DocumentForm( request.user.profile, None, instance=document) context = _get_default_context(request) context.update({'form': form, 'document': document}) return render_to_response('documents/document_edit', context, context_instance=RequestContext(request), response_format=response_format)
def submit_doc(request): ret = {'UserName': None, 'form': None, 'UserInfoObj': None} ret['UserName'] = request.session.get('username', None) #WorkOrderObj = WorkOrder.objects.create() UserInfoObj = UserInfo.objects.get(username=ret['UserName']) ret['UserInfoObj'] = UserInfoObj if request.method == 'POST': DocumentObj_form = DocumentForm(request.POST, request.FILES) upload_filename = request.FILES['attachment'].name #django.core.files.uploadedfile.InMemoryUploadedFile fileSuffixObj = filenameJudge(upload_filename) file_flag = fileSuffixObj.suffix_judge() if DocumentObj_form.is_valid() and file_flag: DocumentObj = DocumentObj_form.save(commit=False) #索引状态放置为b即开始索引 DocumentObj.indexstate = 'b' DocumentObj.save() analyze_uploadfile_task.delay(DocumentObj.id, file_flag) ret['status'] = 'save ok' else: ret['status'] = 'save error' ret['form'] = DocumentObj_form #添加跨站请求伪造的认证 ret.update(csrf(request)) return render(request, 'submitdoc.html', ret) DocumentObj_form = DocumentForm() ret['form'] = DocumentObj_form #添加跨站请求伪造的认证 ret.update(csrf(request)) return render_to_response('submitdoc.html', ret)
def serve_files_list(request, *kwargs): usersession = request.session['name'] if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newfile = FileUpload(file=request.FILES['file']) newfile.save() # print newfile.file user_info = UserFiles(user=usersession, file_id=newfile.id, file_name=newfile.file) user_info.save() return HttpResponseRedirect(reverse('file_uploading')) else: form = DocumentForm() # url = reverse('list', kwargs={'username': classname}) cl = MongoClient() db = cl.my_database #my_database - > database name # gd = GridFS(db,collection = 'storage') #storage - > collection name in which files are stored # file_list = gd.list() # print file_list # file_list = FileUpload.objects.all() #added x = db.gridfsuploads_userfiles.find({'user': usersession}) #{'user':'******'} file_list = [] for rec in x: # file_list[rec.get('file_name')]=rec.get('file_id') file_list.append(rec.get('file_name')) # print file_list return render_to_response('gridfsuploads/fileupload_list.html', { 'fileupload_list': file_list, 'form': form, 'usersession': usersession }, context_instance=RequestContext(request))
def document_add_typed(request, folder_id=None, response_format='html'): "Document add to preselected folder" folder = None if folder_id: folder = get_object_or_404(Folder, pk=folder_id) if not request.user.profile.has_permission(folder, mode='x'): folder = None document = Document() if request.POST: if 'cancel' not in request.POST: form = DocumentForm( request.user.profile, folder_id, request.POST, instance=document) if form.is_valid(): document = form.save() document.set_user_from_request(request) return HttpResponseRedirect(reverse('documents_document_view', args=[document.id])) else: return HttpResponseRedirect(reverse('document_index')) else: form = DocumentForm(request.user.profile, folder_id) context = _get_default_context(request) context.update({'form': form, 'folder': folder}) return render_to_response('documents/document_add_typed', context, context_instance=RequestContext(request), response_format=response_format)
def gerar_arquivo_esforcos(request): if request.method == 'POST': lamina=request.POST['select'] lamina=int(lamina) for p in Laminas.objects.raw('SELECT * FROM macro_laminas where id= %s'%(lamina)): SIGMA_T_1=p.SIGMA_T_1 SIGMA_T_2=p.SIGMA_T_2 SIGMA_C_1=-p.SIGMA_C_1 # Convenio de sinais SIGMA_C_2=-p.SIGMA_C_2 # Convenio de sinais NOME=p.NOME TAU12=p.TAU12 form = DocumentForm() legendaResultado="<a class=\"btn btn-primary\" href=\"/criterios_envelopes_julian/area_programador/Lendo_Arquivo_Teste/%d/\" role=\"button\">Arquivo Gerado %s</a><br><br><b>Foi gerado um arquivo de teste considerando os valores:</b>" % (lamina,NOME) legendaResultado="".join([legendaResultado,"<br> SIGMA_T_1 (Pa): ",str(SIGMA_T_1)]); legendaResultado="".join([legendaResultado,"<br> SIGMA_T_2 (Pa): ",str(SIGMA_T_2)]); legendaResultado="".join([legendaResultado,"<br> SIGMA_C_1 (Pa): ",str(SIGMA_C_1)]); legendaResultado="".join([legendaResultado,"<br> SIGMA_C_2 (Pa): ",str(SIGMA_C_2)]); color_fundo="background-color:gold;" c = { 'form': form, 'legendaResultado':legendaResultado, 'color_fundo':color_fundo, } return render(request,'area_programador/gerarArquivoTeste.htm',c) ####END fo if form = DocumentForm() color_fundo="background-color:powderblue;" c = { 'form': form, 'color_fundo':color_fundo, } return render(request,'area_programador/gerarArquivoTeste.htm',c)
def index(request): if request.method=="POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() greyscale = form.cleaned_data['greyscale'] smoothen = form.cleaned_data['smoothen'] binarythreshold = form.cleaned_data['binarythreshold'] resize = form.cleaned_data['resize'] histogram = form.cleaned_data['histogram'] edgedetection = form.cleaned_data['edgedetection'] sobelfilter = form.cleaned_data['sobelfilter'] foregroundextract = form.cleaned_data['foregroundextract'] stufftodo=[] if(greyscale==True): stufftodo.append("greyscale") if(smoothen==True): stufftodo.append("smoothen") if(binarythreshold==True): stufftodo.append("binarythreshold") if(resize==True): stufftodo.append("resize") if(histogram==True): stufftodo.append("histogram") if(edgedetection==True): stufftodo.append("edgedetection") if(sobelfilter==True): stufftodo.append("sobelfilter") if(foregroundextract==True): stufftodo.append("foregroundextract") imageurlcontainer = process(request,newdoc.docfile.name,stufftodo) return render(request,'polls/showimg.html',{"imageurlcontainer":imageurlcontainer}) else: return HttpResponse("Error brah") else: form = DocumentForm() documents = Document.objects.all() return render(request,'polls/index.html',{"form":form})
def draft_edit(request, id, template_name='doccomment/doc_editor.html'): doc = get_object_or_404(Document, pk=id) if doc.author != request.user and not Permission.user_is_editor(request.user): return HttpResponseForbidden('You can only edit documents you created') if request.method == 'POST': form = DocumentForm(request.POST, instance=doc) if form.is_valid(): doc = form.save(commit=False) doc.has_modification = True doc.save() if request.POST.get('save-and-continue', None): url = reverse('doccomment_draft_edit', kwargs={'id':doc.id}) else: url = reverse('doccomment_draft_list') # TODO: use django-messages to display "saved" message return HttpResponseRedirect(url) else: form = DocumentForm(instance=doc) return render_to_response(template_name, { 'form' : form, 'document' : doc, }, context_instance=RequestContext(request))
def upload_file(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document upload view after POST return HttpResponseRedirect('testMongo.testMongo.views.upload_file') else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render_to_response( 'testMongo/upload.html', {'documents': documents, 'form': form}, context_instance=RequestContext(request) )
def uploadfile(request): if request.method == "POST": doc = DocumentForm(request.POST, request.FILES) if doc.is_valid(): doc.save() return redirect("/home/") form = DocumentForm() return render(request, "uploadfile.html", {"form": form})
def edit_doc(request, doc_id=None): try: doc = Document.objects.get(id=doc_id) except Document.DoesNotExist: return redirect('documents:create_event') if request.method == 'POST': form = DocumentForm(request.POST, request.FILES, instance=doc) if (form.is_valid()): form.save() return redirect(reverse('documents:index')) else: form = DocumentForm(request.POST, request.FILES, instance=event) else: form = DocumentForm(instance=doc) context = { 'form': form, 'form_url': reverse('documents:edit_doc', args=[doc_id]) } return render(request, 'documents/edit_doc.html', context)
def main(request): # Handle file upload if request.method == 'POST': test_form = DocumentForm(request.POST, request.FILES) if test_form.is_valid(): test_form.save() messages.success(request, 'The test was uploaded. Thank you!') return HttpResponseRedirect(reverse('Library.views.main')) textbook_form = AddTextbookForm(request.POST) if textbook_form.is_valid(): textbook_form.save() messages.success(request, 'The record was uploaded. Thank you!') return HttpResponseRedirect(reverse('Library.views.main')) else: test_form = DocumentForm() # A empty, unbound form textbook_form = AddTextbookForm() # A empty, unbound form tests = Test.objects.all() textbooks = Textbook.objects.all() # Render list page with the documents and the form return render_to_response( 'library.html', { 'tests': tests, 'test_form': test_form, 'textbooks': textbooks, 'textbook_form': textbook_form }, context_instance=RequestContext(request) )
def add_file(request, chat_id): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): try: chat = Chat.objects.get(id = chat_id) newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() text = newdoc.docfile message = Message( chat_id = chat, user_id = request.user, message = text, post_time = timezone.now(), _type = 3, ) message.save() return HttpResponse(request.FILES['docfile'].name) except: return HttpResponse('bad') else: form = DocumentForm() return render(request, 'add_file.html', {'form': form } )
def add_document(request): """ Add a document """ dform = DocumentForm(user=request.user) rform = ReferenceForm() if request.method == 'POST': rform = ReferenceForm(request.POST) dform = DocumentForm(request.POST, request.FILES, user=request.user) #this avoids ignoring the evaluation of the form to show the errors rf_is_valid = rform.is_valid() df_is_valid = dform.is_valid() if rf_is_valid and df_is_valid: rform.save() dform.instance.reference = rform.instance dform.save() file = dform.cleaned_data['file'] dform.instance.set_file(file=file, filename=file.name) assign_perm('documents.access_document', request.user, dform.instance) return HttpResponseRedirect(reverse('documents.views.list_documents')) return render_to_response('add_document.html', { 'dform': dform, 'rform': rform, }, context_instance=RequestContext(request))
def display_map(request): errorMessage = None geodata = {} geodata = json.dumps(geodata) if request.method == 'POST': form1 = DocumentForm(request.POST, request.FILES) form = FilterForm(request.POST) bndryform = BndryCondsForm(request.POST, request.FILES) if form1.is_valid() and bndryform.is_valid(): form1.save() bndryform.save() meshpath = request.FILES['document'] bcpath = request.FILES['bndryfile'] kwargs = {} kwargs["proj"] = request.POST['projection'] cwd = os.getcwd() meshpath = cwd + '/documents/' + str(meshpath) bcpath = cwd + '/documents/' + str(bcpath) kwargs["bcfile"] = bcpath mymesh = MESHOBJECT(meshpath, **kwargs) if not mymesh.fileExists: IOError('%s does not exist. Check file name and path' % self.meshfile) errorMessage = ('%s does not exist. Check file name and path' % self.meshfile) else: meshgeojson = mymesh.mesh2GEOJSON() geodata = json.dumps(meshgeojson) meshcentre = mymesh.meshCentre() bndrysgeojson = mymesh.bndry2GEOJSON() request.session['my_data'] = geodata meshcentrestr = str(meshcentre[0]) + "," + str(meshcentre[1]) request.session['centre'] = meshcentrestr request.session['bndrysgeojson'] = bndrysgeojson request.session['meshfile'] = meshpath request.session['bcfile'] = bcpath return HttpResponseRedirect(reverse('model_parameters')) else: form1 = DocumentForm() bndryform = BndryCondsForm() form = FilterForm() return render( request, 'runtide/fileuploadv2.html', { 'form': form, 'form1': form1, 'geodata': geodata, 'errorMessage': errorMessage, 'bndryform': bndryform, })
def index(request): BASE = os.path.dirname(os.path.abspath(__file__)) folder = os.path.abspath(os.path.join(BASE, '..')) folder = os.path.abspath(os.path.join(folder, 'media')) for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): fs = FileSystemStorage() i = 1 for file in request.FILES.getlist('document'): filename = 'Test-' + str(i) + '-1.jpg' pdffilename = 'Test-' + str(i) if (".jpg" in file.name) or (".jpeg" in file.name): fs.save(filename, file) if (".pdf" in file.name): fs.save(file.name, file) pdf_file_path = os.path.join(folder, file.name) pages = convert_from_path(pdf_file_path, output_folder=folder, fmt='jpg', output_file=pdffilename) i = i + 1 execute() filepath = os.path.join(folder, 'Result.jpg') return serve(request, os.path.basename(filepath), os.path.dirname(filepath)) return render(request, 'utility/index.html', {'form': form}) else: form = DocumentForm() return render(request, 'utility/index.html', {'form': form})