def getMessages(request): message_id = request.POST["id"] arxiv_no = request.POST["arxivno"] renderList = [] template = loader.get_template("message.html") commenttemplate = loader.get_template("comment.html") # If the paper has an arXiv number we search for it in the databases if arxiv_no != "0": if newPaper.objects.filter(arxiv_no=arxiv_no).count() == 1: article = newPaper.objects.get(arxiv_no=arxiv_no) elif Paper.objects.filter(arxiv_no=arxiv_no).count() == 1: article = Paper.objects.get(arxiv_no=arxiv_no) else: article = "NONE" # If the paper has an Inspires number but no arXiv number so we only check the Paper database else: if Paper.objects.filter(Inspires_no=str(message_id)).count() == 1: article = Paper.objects.get(Inspires_no=str(message_id)) else: article = "NONE" if article != "NONE": posts = article.post_set.all() for p in posts: commentList = [] subcomments = p.comment_set.all() for x in subcomments: context = {"message": x.comment, "time": x.date, "user": x.commenter.username} temp = str(commenttemplate.render(context).encode("utf8")) commentList.append(temp) context = { "message": p.message, "time": p.date, "number": p.messageID, "user": p.poster, "upvotes": p.upVotes, } renderList.append( {"post": str(template.render(context).encode("utf8")), "comments": commentList, "id": p.messageID} ) return JsonResponse({"messageHTML": renderList})
def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = RequestContext(request, { 'latest_question_list': latest_question_list, }) return HttpResponse(template.render(context))
def get(self, request, pk, catastropheForm : CatastropheEditForm = None): templatePath = 'dcp/content/adminstrator/catastropheEdit.html' template = loader.get_template(templatePath) catastrophe = get_object_or_404(Catastrophe, id=pk) user = request.user if not catastrophe.isAbleToEdit(user): return HttpResponseForbidden(render(request, 'dcp/content/spezial/403.html')) if catastropheForm is None: catastropheForm = CatastropheEditForm(initial={'radius' : catastrophe.radius, 'maxOutsideRadius': catastrophe.maxOutsideRadius}) ngos = Ngo.objects.exclude(catastrophes=catastrophe) ngoChoices = [('', 'Keine neue NGO')] for ngo in ngos: ngoChoices.append((ngo.id, ngo.name)) catastropheForm['ngo'].field.choices = ngoChoices governments = Government.objects.exclude(catastrophes=catastrophe) governmentChoices = [('', 'Keine neue Regierung')] for government in governments: governmentChoices.append((government.id, government.name)) catastropheForm['government'].field.choices = governmentChoices context={ 'catastrophe' : catastrophe, 'catastropheForm' : catastropheForm } return HttpResponse(template.render(context, request))
def teams(request): template = loader.get_template('teamlogic/teams.html') teams = models.Team.objects.all() context = RequestContext(request, { 'teams': teams }) return HttpResponse(template.render(context))
def q_500(request): template = loader.get_template('questionnaire/q_500.html') context = RequestContext(request) response = HttpResponse(template.render(context), status=500) return response
def loginusr(request): """ View da página de Login Tem duas funções: Processar o reset de senha e fazer o Login. LOGIN: Verifica se o usuário e senhas estão no sistema, caso contrário, informa respectivas mensagens de erro. PASS RESET: Reseta a senha de acordo com o usuário informado, enviando por email a nova senha gerada randomicamente. @param request: @return: """ template = loader.get_template('login/login.html') page = sitemap ( request.get_full_path ( ) ).context context = {} if request.POST: username = request.POST['mail'] password = request.POST['password'] if 'email-reset' in request.POST: reset_mail = request.POST['email-reset'] try: user_reset = User.objects.get(username__exact=reset_mail) if user_reset: pass_reset = pass_generator() user_reset.set_password(pass_reset) user_reset.save() email_corpo = u"Sua senha foi alterada no sistema. SUA NOVA SENHA É: "+pass_reset email_titulo = u"Senha Resetada" email_destino = [user_reset.email] send_mail(email_titulo, email_corpo, settings.EMAIL_HOST_USER, email_destino) state = {'msg': u"Um email foi enviado para sua caixa de entrada contendo sua nova senha.", 'mode': 'sucess'} else: state = {'msg': u'Usuário não existe no banco de dados.', 'mode': 'error'} except: state = {'msg': u"Ocorreu um erro ao redefinir sua senha.", 'mode': 'error'} else: redirect_to = request.POST.get('next', request.GET.get('next', '')) if not http.is_safe_url(redirect_to, request.get_host()): redirect_to = '/home/' user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request,user) return redirect(redirect_to) else: state = {'msg': u"Sua conta esta desativada, por favor entre em contato com o administrador..", 'mode': 'warning'} else: state = {'msg': u"Usuário ou senha incorretos.", 'mode': 'error'} context['state'] = state context['username'] = username context.update(page) req_context = RequestContext(request, context) return HttpResponse(template.render(req_context))
def filter_subscribe(request, username, name): filter = get_object_or_404(TestRunFilter, owner__username=username, name=name) if not request.user.is_superuser: if not filter.public and filter.owner != request.user: raise PermissionDenied() try: subscription = TestRunFilterSubscription.objects.get( user=request.user, filter=filter) except TestRunFilterSubscription.DoesNotExist: subscription = None if request.method == "POST": form = TestRunFilterSubscriptionForm( filter, request.user, request.POST, instance=subscription) if form.is_valid(): if 'unsubscribe' in request.POST: subscription.delete() else: form.save() return HttpResponseRedirect(filter.get_absolute_url()) else: form = TestRunFilterSubscriptionForm( filter, request.user, instance=subscription) template = loader.get_template('dashboard_app/filter_subscribe.html') return HttpResponse(template.render( { 'filter': filter, 'form': form, 'subscription': subscription, 'bread_crumb_trail': BreadCrumbTrail.leading_to( filter_subscribe, name=name, username=username), }, request=request) )
def image_report_display(request, name): image_report = get_object_or_404(ImageReport, name=name) if not request.user.is_superuser: if not image_report.is_published and image_report.user != request.user: raise PermissionDenied if not image_report.is_accessible_by(request.user): raise PermissionDenied() chart_data = {} for index, chart in enumerate( image_report.imagereportchart_set.all().order_by( 'relative_index')): chart_data[index] = chart.get_chart_data(request.user) template = loader.get_template('dashboard_app/image_report_display.html') return HttpResponse(template.render( { 'image_report': image_report, 'chart_data': simplejson.dumps(chart_data), 'bread_crumb_trail': BreadCrumbTrail.leading_to( image_report_detail, name=name), }, request=request) )
def testjob(request, job): job = get_restricted_job(request.user, pk=job, request=request) data = ResultsView(request, model=TestSuite, table_class=TestJobResultsTable) suite_table = TestJobResultsTable( data.get_table_data().filter(job=job) ) failed_definitions = [] yaml_dict = OrderedDict() if TestData.objects.filter(testjob=job).exists(): # some duplicates can exist, so get would fail here and [0] is quicker than try except. testdata = TestData.objects.filter( testjob=job).prefetch_related('actionlevels__testcase', 'actionlevels__testcase__suite')[0] if job.state == TestJob.STATE_FINISHED: # returns something like ['singlenode-advanced', 'smoke-tests-basic', 'smoke-tests-basic'] executed = [ { case.action_metadata['test_definition_start']: case.action_metadata.get('success', '')} for case in TestCase.objects.filter( suite__in=TestSuite.objects.filter(job=job)) if case.action_metadata and 'test_definition_start' in case.action_metadata and case.suite.name == 'lava'] submitted = [ actiondata.testcase.action_metadata for actiondata in testdata.actionlevels.all() if actiondata.testcase and 'test-runscript-overlay' in actiondata.action_name] # compare with a dict similar to created in executed for item in submitted: if executed and {item['name']: item['success']} not in executed: comparison = {} if item['from'] != 'inline': comparison['repository'] = item['repository'] comparison['path'] = item['path'] comparison['name'] = item['name'] comparison['uuid'] = item['success'] failed_definitions.append(comparison) # hide internal python objects, like OrderedDict for data in testdata.attributes.all().order_by('name'): yaml_dict[str(data.name)] = str(data.value) RequestConfig(request, paginate={"per_page": suite_table.length}).configure(suite_table) template = loader.get_template("lava_results_app/job.html") return HttpResponse(template.render( { 'bread_crumb_trail': BreadCrumbTrail.leading_to(testjob, job=job.id), 'job': job, 'job_link': pklink(job), 'suite_table': suite_table, 'metadata': yaml_dict, 'failed_definitions': failed_definitions, 'condition_choices': simplejson.dumps( QueryCondition.get_condition_choices(job) ), 'available_content_types': simplejson.dumps( QueryCondition.get_similar_job_content_types() ), }, request=request))
def common_render(template_path, context_data): from django.shortcuts import loader from django.template import Context t = loader.get_template(template_path) c = Context(context_data) return t.render(c)
def new_product(request): template = loader.get_template('new_product.html') form = ProductForm() context = [ HttpResponse(template.render(context, request)) ]
def cityes(request): template = loader.get_template('cityes.html') elements = requests.get('http://127.0.0.1:5000/cityes') context = { "elements": elements.json(), } return render(request, 'cityes.html', context)
def hola(request): ''' --------------------------------------------------------------------------------------- #return HttpResponse('hola chicos') ---> no sera utilizado por ahora #ocupamos render para traer el html index.html ##return render(request, 'index.html') ----> no es utilizado por ahora --------------------------------------------------------------------------------------- ''' ''' creamos una variable llamada product y a esa variable le pasamos el objeto Product y pedimos que los ordene por el id ''' product = Product.objects.order_by('id') ''' creamos una variable llamada template y en esa variable a travez del metodo loader traemos la pagina index.html con la funcion get_template() ''' template = loader.get_template('index.html') ''' el contexto servira para poder ocupar todos los datos respecto a el objeto product y llevarlos a index.html para ser ocupados alla con sintaxis django ''' context = { 'product': product } #le enviamos el contexto y el request a traves del httpResponse return HttpResponse(template.render(context, request))
def product_detail(request, pk): product = get_object_or_404(Product, pk=pk) template = loader.get_template('product_detail.html') context = { 'product': product } return HttpResponse(template.render(context, request))
def edit_post(request): template = loader.get_template('edit_post.html') context = {'has_text': True} if request.method == 'GET': if 'post_id' in request.GET: post_id = request.GET['post_id'] post = get_object_or_404(BlogPost, pk=post_id) context['post_text'] = post.text context['edited'] = post_id return HttpResponse(template.render(context)) elif request.method == 'POST': if 'text' not in request.POST or \ request.POST['text'].strip() == '': context['has_text'] = False return HttpResponse(template.render(context)) else: if 'edited' in request.POST and request.POST['edited']!='': blogpost = BlogPost.objects.get(pk=request.POST['edited']) else: blogpost = BlogPost() blogpost.text = request.POST['text'] blogpost.save() return redirect("/index") else: return HttpResponse(status=405)
def common_render(template_path, context_data): from django.shortcuts import loader from django.template import Context t = loader.get_template("email/_email.html") c = Context({"mail": email}) return t.render(c)
def index(request): latest_question_list = Questions.objects.order_by("-pub_date")[:5] template = loader.get_template("polls/index.html") context_page = { "latest_question_list" : latest_question_list, } return HttpResponse(template.render(context_page, request))
def image_chart_filter_detail(request, name, id, slug): if request.method == 'POST': # Saving image chart test. chart_test = _get_image_chart_test( slug, request.POST.get('chart_test_id')) request.POST.get('attributes') chart_test.name = request.POST.get('alias') chart_test.attributes = request.POST.getlist('attributes') chart_test.save() chart_filter = get_object_or_404(ImageChartFilter, id=slug) image_chart = chart_filter.image_chart xaxis_attribute_changed = False supported_attrs = image_chart.get_supported_attributes(request.user) if image_chart.xaxis_attribute: if not supported_attrs or \ image_chart.xaxis_attribute not in supported_attrs: image_chart.xaxis_attribute = None image_chart.save() xaxis_attribute_changed = True template = loader.get_template('dashboard_app/image_chart_filter_detail.html') return HttpResponse(template.render( { 'chart_filter': chart_filter, 'xaxis_attribute_changed': xaxis_attribute_changed, 'bread_crumb_trail': BreadCrumbTrail.leading_to( image_chart_filter_detail, name=name, id=id, slug=slug), }, request=request) )
def suite(request, job, pk): job = get_restricted_job(request.user, pk=job, request=request) test_suite = get_object_or_404(TestSuite, name=pk, job=job) data = SuiteView(request, model=TestCase, table_class=SuiteTable) suite_table = SuiteTable( data.get_table_data().filter(suite=test_suite) ) RequestConfig(request, paginate={"per_page": suite_table.length}).configure(suite_table) template = loader.get_template("lava_results_app/suite.html") return HttpResponse(template.render( { 'bread_crumb_trail': BreadCrumbTrail.leading_to(suite, pk=pk, job=job.id), 'job': job, 'job_link': pklink(job), 'testsuite_content_type_id': ContentType.objects.get_for_model( TestSuite).id, 'suite_name': pk, 'suite_id': test_suite.id, 'suite_table': suite_table, 'bug_links': BugLink.objects.filter( object_id=test_suite.id, content_type_id=ContentType.objects.get_for_model( TestSuite).id, ) }, request=request))
def image_report_list(request): imagesets = ImageSet.objects.filter() imagesets_data = [] for imageset in imagesets: images_data = [] for image in imageset.images.all(): # Migration hack: Image.filter cannot be auto populated, so ignore # images that have not been migrated to filters for now. if image.filter: filter_data = image.filter.as_data() is_accessible = True for stream in image.filter.bundle_streams.all(): if not stream.is_accessible_by(request.user): is_accessible = False break image_data = { 'name': image.name, 'is_accessible': is_accessible, 'link': image.name, } images_data.append(image_data) images_data.sort(key=lambda d: d['name']) imageset_data = { 'name': imageset.name, 'images': images_data, } imagesets_data.append(imageset_data) imagesets_data.sort(key=lambda d: d['name']) template = loader.get_template("dashboard_app/image-reports.html") return HttpResponse(template.render( { 'bread_crumb_trail': BreadCrumbTrail.leading_to(image_report_list), 'imagesets': imagesets_data, }, request=request))
def recet_detail(request, pk): recetad = get_object_or_404(Receta, pk=pk) template = loader.get_template('recet_detail.html') context = { 'receta_detalles': recetad } return HttpResponse(template.render(context, request))
def hello_mundo(request): receta_org = Receta.objects.order_by('id') template = loader.get_template('index.html') context = { 'recetitas': receta_org } return HttpResponse(template.render(context, request))
def query_form(request, bread_crumb_trail, instance=None, is_copy=False): if request.method == 'POST': form = QueryForm(request.user, request.POST, instance=instance, is_copy=is_copy) if form.is_valid(): query = form.save() if request.GET.get("conditions"): conditions = Query.parse_conditions( query.content_type, request.GET.get("conditions")) for condition in conditions: condition.query = query condition.save() return HttpResponseRedirect(query.get_absolute_url() + "/+detail") else: form = QueryForm(request.user, instance=instance, is_copy=is_copy) form.fields['owner'].initial = request.user query_name = None if is_copy: query_name = instance.name instance.name = None template = loader.get_template('lava_results_app/query_form.html') return HttpResponse(template.render( { 'bread_crumb_trail': bread_crumb_trail, 'is_copy': is_copy, 'query_name': query_name, 'form': form, 'context_help': ['lava-queries-charts'], }, request=request))
def lista_encuestas(request, en, en2): template = loader.get_template('encuestas/list.html') #clases. horrible, but works. if en2 == "-1": nombre_clase = Clase.objects.get(id = en) encuestas = [(i.fecha_creacion,i.id) for i in Encuesta.objects.filter(clase = en).order_by('-fecha_creacion')] entity_name =nombre_clase.nombre else: nombre_clase = Clase.objects.get(id = en) nombre_profesor = Profesor.objects.get(id = en2) encuestas = [(i.fecha_creacion,i.id) for i in Encuesta.objects.filter(clase = en , profesor = en2).order_by('-fecha_creacion')] entity_name = nombre_profesor.nombre #nothing was found if not encuestas: encuestas = list() sorted_encuestas = list() else: #store in dictionary, to organize in years. sorted_encuestas = list() for enc in encuestas: encuesta = {'year' : enc[0].year, 'value':enc[0], 'id': enc[1]} sorted_encuestas.append(encuesta) context = {'entity_type': "1", 'entity_id' : en, 'entity': entity_name, 'encuestas': encuestas, 'sorted_encuestas':sorted_encuestas} return HttpResponse(template.render(context, request))
def help(request, mapper, template_name="linaro_django_xmlrpc/api.html"): # pylint: disable=redefined-builtin context = CallContext( user=None, mapper=mapper, dispatcher=None, request=request) system = SystemAPI(context) scheme = request.META.get('REQUEST_SCHEME', "http") dashboard_methods = [] scheduler_methods = [] results_methods = [] system_methods = [] for method in system.listMethods(): if 'dashboard' in method: dashboard_methods.append(method) elif 'scheduler' in method: scheduler_methods.append(method) elif 'results' in method: results_methods.append(method) else: system_methods.append(method) methods = { 'dashboard': [ { 'name': method, 'signature': system.methodSignature(method), 'help': system.methodHelp(method) } for method in dashboard_methods ], 'scheduler': [ { 'name': method, 'signature': system.methodSignature(method), 'help': system.methodHelp(method) } for method in scheduler_methods ], 'results': [ { 'name': method, 'signature': system.methodSignature(method), 'help': system.methodHelp(method) } for method in results_methods ], 'system': [ { 'name': method, 'signature': system.methodSignature(method), 'help': system.methodHelp(method) } for method in system_methods ]} template = loader.get_template(template_name) return HttpResponse(template.render({ 'methods': methods, 'context_help': ['data-export'], 'site_url': "{scheme}://{domain}".format( scheme=scheme, domain=Site.objects.get_current().domain) }, request=request))
def index(request): template = loader.get_template('usermanagement/index.html') message = messages.objects.all() billboard = billboards.objects.all() user_pols = user_policy.objects.all() context = RequestContext(request, {'Messages': message,'billboards': billboard,'users':user_pols}) return HttpResponse(template.render(context))
def stadion(request, id): template = loader.get_template('teamlogic/stadion.html') stadion = get_object_or_404(models.Stadium, pk=id) context = RequestContext(request, { 'stadion': stadion, 'user': request.user, }) return HttpResponse(template.render(context))
def stadions(request): template = loader.get_template('teamlogic/stadions.html') stadions = models.Stadium.objects.all() context = RequestContext(request,{ 'stadions': stadions, 'user': request.user }) return HttpResponse(template.render(context))
def index(request): template = loader.get_template('encuestas/index.html') profesores = [(i.nombre,i.id) for i in Profesor.objects.all()] clases = [(i.nombre,i.id) for i in Clase.objects.all()] context = { 'profesores': profesores, 'clases': clases} return HttpResponse(template.render(context, request))
def handler500(request): template = loader.get_template('error/500.html') context = Context({ 'message':'HTTP 500:: 서버 에러 입니다.', }) return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=500)
def hello_user(request): template = loader.get_template('hello_user.html') context = {"name": None} return HttpResponse(template.render(context, request))
def work_admin_record_details(request): if request.method == "GET": user_name = request.COOKIES.get('username', '') staff_name = request.GET.get('search', '') search_name = staff_name start_time = request.GET.get('start_time', '') end_time = request.GET.get('end_time', '') work_condition = {} if staff_name != "": work_condition["staff_name__contains"] = staff_name if start_time != "": if end_time != "": work_condition["start_time__range"] = (start_time, end_time) if not work_condition: work_his = Work_time.objects.all().order_by("-update_time") else: work_his = Work_time.objects.filter( **work_condition).order_by("-update_time") page = request.GET.get('page') if page == "all": work_time = Work_time.objects.filter( staff_name=staff_name).aggregate(Sum('duration_number')) staff_name = staff_name.encode('utf-8') work_content = "%s :还剩下 %s 小时的加班时长!!!" % ( staff_name, work_time['duration_number__sum']) t = loader.get_template("work_admin_details.html") c = Context({ 'work_his': work_his, 'staff_name': staff_name, 'work_time': work_content, 'user_name': user_name, 'search_name': search_name, 'start_time': start_time, 'end_time': end_time }) return HttpResponse(t.render(c)) else: limit = 10 work_time = Work_time.objects.filter( staff_name=staff_name).aggregate(Sum('duration_number')) staff_name = staff_name.encode('utf-8') work_content = "%s :还剩下 %s 小时的加班时长!!!" % ( staff_name, work_time['duration_number__sum']) print staff_name print work_content paginator = Paginator(work_his, limit) try: show_details = paginator.page(page) except PageNotAnInteger: show_details = paginator.page(1) except EmptyPage: show_details = paginator.page(paginator.num_pages) t = loader.get_template("work_admin_details.html") c = Context({ 'work_his': show_details, 'staff_name': staff_name, 'work_time': work_content, 'user_name': user_name, 'search_name': search_name, 'start_time': start_time, 'end_time': end_time }) return HttpResponse(t.render(c))
def otpbuttonview(request): return HttpResponse( loader.get_template('redirectpage.html').render({}, request))
def index(request): cadets = Cadet.objects.all() context = {'cadets': cadets} template = loader.get_template('cadettracker/index.html') return HttpResponse(template.render(context, request))
def info_main(request): office_staff = OfficeStaff.objects.all() template = loader.get_template('info/info_main.html') return HttpResponse( template.render({'office_staff': office_staff}, request))
def index(request): context = {} template = loader.get_template('dataGetter/index.html') return HttpResponse(template.render(context, request))
def notice(request): template = loader.get_template('notice.html') context = {} return HttpResponse(template.render(context, request))
def regist(request): template = loader.get_template('regist.html') context = {} return HttpResponse(template.render(context, request))
def get(self, request): if not request.user.is_authenticated: return HttpResponseRedirect("/login") context = {} template = loader.get_template("account/main_settings.html") return HttpResponse(template.render(context, request))
def index(request): template = loader.get_template('curr_res/base_curr_res.html') return HttpResponse(template.render(request))
def summary(request, planid): c = dict(plans=ImplementationPlan.objects.filter(id=planid)) for plan in c['plans']: plan.recompute_plan() t = loader.get_template("summary.html") return HttpResponse(t.render(c))
def query(request): template = loader.get_template("lava_results_app/query_list.html") return HttpResponse( template.render( {"bread_crumb_trail": BreadCrumbTrail.leading_to(index)}, request=request))
def index(request): files = [] temp = 'web/login.html' msg = "" sucf = 1 if request.method == 'POST' and 'name' in request.POST: try: name = request.POST.get('name') email = request.POST.get('email') try: user = models.Participants.objects.get(email=email) request.session['id'] = user.id request.session['name'] = user.full_name request.session['email'] = user.email if user.is_completed is True: msg = "already_completed" temp = 'web/login.html' else: fls = models.Files.objects.filter(status=True) for i in fls: try: f = models.UserFiles.objects.get( file_details_id=i.id, participant_id=user.id) except: f = models.UserFiles() f.participant_id = user.id f.file_details_id = i.id f.save() files = models.UserFiles.objects.filter( participant_id=user.id) sucf = models.UserFiles.objects.filter( participant_id=user.id, is_downloaded=False).count() msg = "not_completed" temp = 'web/index.html' except: user = models.Participants() user.full_name = name user.email = email user.save() fls = models.Files.objects.filter(status=True) for i in fls: f = models.UserFiles() f.participant_id = user.id f.file_details_id = i.id f.save() files = models.UserFiles.objects.filter(participant_id=user.id) sucf = models.UserFiles.objects.filter( participant_id=user.id, is_downloaded=False).count() request.session['id'] = user.id request.session['name'] = user.full_name request.session['email'] = user.email msg = "started" temp = 'web/index.html' except: msg = "error" temp = 'web/login.html' if request.method == 'POST' and 'fid' in request.POST: f = models.UserFiles.objects.get(id=request.POST.get('fid')) f.is_downloaded = True f.save() f.file_details.downloads = int(f.file_details.downloads) + 1 f.file_details.save() sucf = models.UserFiles.objects.filter(participant_id=f.participant_id, is_downloaded=False).count() if sucf == 0: f.participant.is_files_downloaded = True f.participant.save() download = f.file_details.file.url files = models.UserFiles.objects.filter( participant_id=f.participant_id) request.session['id'] = f.participant_id request.session['name'] = f.participant.full_name request.session['email'] = f.participant.email msg = "started" temp = 'web/index.html' if request.method == 'POST' and 'location' in request.POST: user = models.Participants.objects.get(id=request.session['id']) location = request.POST.get('location') job = request.POST.get('job') industry = request.POST.get('industry') affects = request.POST.get('question_3') des = request.POST.get('description') sur = models.SurveyResult() sur.participant_id = user.id sur.location = location sur.job = job sur.industry = industry if affects == "Yes": sur.corona_affects_financially = True else: sur.corona_affects_financially = False sur.lockdown_activites = des sur.save() user.is_completed = True user.save() msg = "completed" temp = 'web/login.html' template = loader.get_template(temp) return HttpResponse( template.render({ 'files': files, 'msg': msg, 'sucf': sucf }, request))
logger.info("Unable to load extra case metadata for %s", extra_case) continue extra_data = f_metadata.get("extra") try: if extra_data and os.path.exists(extra_data): with open(f_metadata["extra"], "r") as extra_file: items = yaml.load(extra_file, Loader=yaml.CLoader) # hide the !!python OrderedDict prefix from the output. for key, value in items.items(): extra_source.setdefault(extra_case.id, "") extra_source[extra_case.id] += "%s: %s\n" % (key, value) except TypeError: # In some old version of LAVA, extra_data is not a string but an OrderedDict # In this case, just skip it. pass template = loader.get_template("lava_results_app/case.html") trail_id = case.id if case else test_sets.first().name return HttpResponse( template.render( { "bread_crumb_trail": BreadCrumbTrail.leading_to( testcase, pk=test_suite.name, job=job.id, case_id=trail_id ), "job": job, "sets": test_sets, "suite": test_suite, "job_link": pklink(job), "extra_source": extra_source, "test_cases": test_cases, "bug_links": BugLink.objects.filter( object_id__in=test_cases.values_list("id", flat=True),
def detail(request, staff_id): member = OfficeStaff.objects.get(pk=staff_id) template = loader.get_template('info/detail.html') return HttpResponse(template.render({'member': member}, request))
def testjob(request, job): job = get_restricted_job(request.user, pk=job, request=request) data = ResultsView(request, model=TestSuite, table_class=TestJobResultsTable) suite_table = TestJobResultsTable(data.get_table_data().filter(job=job)) failed_definitions = [] yaml_dict = OrderedDict() if TestData.objects.filter(testjob=job).exists(): # some duplicates can exist, so get would fail here and [0] is quicker than try except. testdata = TestData.objects.filter(testjob=job).prefetch_related( "actionlevels__testcase", "actionlevels__testcase__suite" )[0] if job.state == TestJob.STATE_FINISHED: # returns something like ['singlenode-advanced', 'smoke-tests-basic', 'smoke-tests-basic'] executed = [ { case.action_metadata[ "test_definition_start" ]: case.action_metadata.get("success", "") } for case in TestCase.objects.filter( suite__in=TestSuite.objects.filter(job=job) ) if case.action_metadata and "test_definition_start" in case.action_metadata and case.suite.name == "lava" ] submitted = [ actiondata.testcase.action_metadata for actiondata in testdata.actionlevels.all() if actiondata.testcase and "test-runscript-overlay" in actiondata.action_name ] # compare with a dict similar to created in executed for item in submitted: if executed and {item["name"]: item["success"]} not in executed: comparison = {} if item["from"] != "inline": comparison["repository"] = item["repository"] comparison["path"] = item["path"] comparison["name"] = item["name"] comparison["uuid"] = item["success"] failed_definitions.append(comparison) # hide internal python objects, like OrderedDict for data in testdata.attributes.all().order_by("name"): yaml_dict[str(data.name)] = str(data.value) RequestConfig(request, paginate={"per_page": suite_table.length}).configure( suite_table ) template = loader.get_template("lava_results_app/job.html") return HttpResponse( template.render( { "bread_crumb_trail": BreadCrumbTrail.leading_to(testjob, job=job.id), "job": job, "job_link": pklink(job), "suite_table": suite_table, "metadata": yaml_dict, "failed_definitions": failed_definitions, "condition_choices": simplejson.dumps( QueryCondition.get_condition_choices(job) ), "available_content_types": simplejson.dumps( QueryCondition.get_similar_job_content_types() ), }, request=request, ) )
def hero(request, name): hero = Heroes.objects.filter(name=name) t = loader.get_template('hero.html') c = dict({'heroSelect': hero}) return HttpResponse(t.render(c))
def resident_home(request): template = loader.get_template('curr_res/curr_res_home.html') return HttpResponse(template.render(request))
def home(request): template = loader.get_template('StaticPages/home.html') context = {} return HttpResponse(template.render(context, request))
def signup(request): ctx = Context({'error': None}) next = "" if request.method == "GET": profile_form = ProfilesForm() next = request.GET.get("next", "/") elif request.method == "POST": profile_form = ProfilesForm(request.POST, request.FILES) print profile_form.is_valid() if profile_form.is_valid(): valid_error = False email = request.POST['email'].strip() password = request.POST['password'] password_confirm = request.POST['password_confirm'] nick_name = request.POST['nick_name'] next = request.POST.get("next", "/") if password != password_confirm: profile_form.add_error('password', '비밀번호가 일치하지 않습니다. 정확히 입력해주세요.') valid_error = True #upload image or user defualt if bool(request.FILES): image_type = request.FILES['pro_photo'].content_type if image_type != 'image/png' and image_type != 'image/jpeg': profile_form.add_error('pro_photo', 'jpg와 png 형식의 이미지만 가능합니다.') valid_error = True try: t = handle_uploaded_image(request.FILES['pro_photo'], 50, 50) content = t[1] except: image_file = open( os.path.join(settings.BASE_DIR, 'resource/image/default_profile.jpg'), 'r') content = ImageFile(image_file) else: image_file = open( os.path.join(settings.BASE_DIR, 'resource/image/default_profile.jpg'), 'r') content = ImageFile(image_file) if valid_error: return render( request, 'user/signup.html', { 'profileform': profile_form, }, ) User = get_user_model() _u = User(username=email) _u.set_password(password) _u.save() #chang form _profile = Profile(user=_u, email=email, pro_photo=content, nick_name=nick_name) _profile.save() #send_email confirm import string, random key = "" while True: for i in xrange(32): key = key+random.choice(string.ascii_letters\ +string.digits) if (SignupConfirmKey.find(key) == None): break #save the key conkey = SignupConfirmKey(key=key, user=_profile) conkey.save() host = request.META['HTTP_HOST'] #write email tpl_mail = loader.get_template( 'contents/mail_form/mail_confirm.html') ctx_mail = Context({ 'host': host, 'key': key, }) cont = tpl_mail.render(ctx_mail) recipient = [_profile.email] if Local: #sendmail not celery from django.core.mail import send_mail send_mail(u'안녕하세요! 토마킷입니다. 정식 사용을 승인해주세요.', "", \ '*****@*****.**', recipient, fail_silently=False, html_message=cont) else: tasks.sendmail.delay(cont, recipient) return HttpResponseRedirect("/user/login/?next=" + next) return render( request, 'contents/user/signup.html', { 'profileform': profile_form, 'next': next, }, )
def forgotpassword(request): template = loader.get_template('forgotpassword.html') msg = '' color = '' smsg = '' usr = '' if request.method == 'POST' and 'resend' in request.POST: try: username = request.POST.get('username2') User = models.CustUser.objects.get(username=username) otp_db = models.Otp.objects.get(user_id=User.id) def otpsenting(user): subject = 'Action Required' from_email = settings.EMAIL_HOST_USER email = user.email otp = otp_db.token message = 'Click this link to recover your email.\n\n http://127.0.0.1:8000/' + str( user.id) + '/' + str(otp) + '/' send_mail(subject=subject, from_email=from_email, message=message, recipient_list=(email, ), fail_silently=False) def otp_btn_email(user): subject = "Password Reset" otp = otp_db.token link = 'http://127.0.0.1:8000/' + str( user.id) + '/' + str(otp) + '/' data = loader.get_template('otpbutton.html') content = data.render({ 'name': user.username, 'link': link, }) from_email = settings.EMAIL_HOST_USER to = user.email msg = EmailMessage(subject, content, from_email, [to]) msg.content_subtype = "html" # Main content is now text/html msg.send() otp_btn_email(User) except socket.gaierror: smsg = "gaiError" if request.method == 'POST' and 'mainform' in request.POST: username = request.POST.get('username') def otpsenting(user): subject = 'Action Required' from_email = settings.EMAIL_HOST_USER email = user.email otp = random.randint(10000, 99999) otp_db = models.Otp() otp_db.user = models.CustUser.objects.get(username=user.username) otp_db.token = otp otp_db.save() message = 'Click this link to recover your email.\n\n http://127.0.0.1:8000/' + str( user.id) + '/' + str(otp) + '/' send_mail(subject=subject, from_email=from_email, message=message, recipient_list=(email, ), fail_silently=False) try: user = models.CustUser.objects.get(username=username) otpsenting(user) msg = 'Recover link sent to mail' color = 'white' except models.CustUser.DoesNotExist: msg = 'Invalid Username' color = 'red' except IntegrityError: smsg = 'intError' usr = request.POST.get("username") except socket.gaierror: smsg = 'gaiError' return HttpResponse( template.render({ 'msg': msg, 'color': color, 'smsg': smsg, 'usr': usr }, request))
def matching(request): form = ReactionForm(request.GET) form.load(request.user.id) context = {'form': form} template = loader.get_template('matching.html') return HttpResponse(template.render(context, request))
def property_details(request): if request.method == "GET": user_name = request.COOKIES.get('username', '') staff_name = user_info(user_name) search_team_name = request.GET.get('search_team', '') search_domain_name = request.GET.get('search_domain', '') search_ip_name = request.GET.get('search_ip', '') search_remark_name = request.GET.get('search_remark', '') search_app_name = request.GET.get('search_app', '') search_system_name = request.GET.get('search_system', '') search_xen_name = request.GET.get('search_xen_name', '') search_xen_ip = request.GET.get('search_xen_ip', '') rank_ip = request.GET.get('rank_ip') rank_domain = request.GET.get('rank_domain') rank_name = "" if rank_ip == "rank_ip": rank_name = "ip_name" elif rank_domain == "rank_domain": rank_name = "domain_name" property_condition = {} if search_team_name != "": property_condition["team_name__contains"] = search_team_name if search_domain_name != "": property_condition["domain_name__contains"] = search_domain_name if search_ip_name != "": property_condition["ip_name__contains"] = search_ip_name if search_remark_name != "": property_condition["ip_remark__contains"] = search_remark_name if search_app_name != "": property_condition["app_name__contains"] = search_app_name if search_system_name != "": property_condition["system_name__contains"] = search_system_name if search_xen_name != "": property_condition["xen_name__contains"] = search_xen_name if search_xen_ip != "": property_condition["xen_ip__contains"] = search_xen_ip if not property_condition: if rank_name != "": property_his = Property_content.objects.all().order_by( rank_name) else: property_his = Property_content.objects.all().order_by( "-update_time") else: if rank_name != "": property_his = Property_content.objects.filter( **property_condition).order_by(rank_name) else: property_his = Property_content.objects.filter( **property_condition).order_by("-update_time") property_number = len(property_his) page = request.GET.get('page') if page == "all": t = loader.get_template("property_details.html") c = Context({ 'property_his': property_his, 'search_team_name': search_team_name, 'search_domain_name': search_domain_name, 'search_ip_name': search_ip_name, 'search_remark_name': search_remark_name, 'search_app_name': search_app_name, 'search_system_name': search_system_name, 'search_xen_name': search_xen_name, 'search_xen_ip': search_xen_ip, 'rank_ip': rank_ip, 'rank_domain': rank_domain }) return HttpResponse(t.render(c)) else: limit = 20 paginator = Paginator(property_his, limit) try: show_details = paginator.page(page) except PageNotAnInteger: show_details = paginator.page(1) except EmptyPage: show_details = paginator.page(paginator.num_pages) t = loader.get_template("property_details.html") c = Context({ 'property_his': show_details, 'search_team_name': search_team_name, 'search_domain_name': search_domain_name, 'search_ip_name': search_ip_name, 'search_remark_name': search_remark_name, 'search_app_name': search_app_name, 'search_system_name': search_system_name, 'search_xen_name': search_xen_name, 'search_xen_ip': search_xen_ip, 'rank_ip': rank_ip, 'rank_domain': rank_domain, 'property_number': property_number }) return HttpResponse(t.render(c))
def MoviesCount(request): c = Movie.objects.values("name", "count").order_by("id") template = loader.get_template("testapp/count.html") result = template.render(context={"jails": c}) return HttpResponse(result)
def query_list(request): group_tables = {} terms_data = search_data = discrete_data = {} for group in QueryGroup.objects.all(): if group.query_set.count(): prefix = "group_%s_" % group.id group_view = GroupQueryView(request, group, model=Query, table_class=GroupQueryTable) table = GroupQueryTable(group_view.get_table_data(prefix), request=request, prefix=prefix) search_data.update(table.prepare_search_data(group_view)) discrete_data.update(table.prepare_discrete_data(group_view)) terms_data.update(table.prepare_terms_data(group_view)) group_tables[group.name] = table config = RequestConfig(request, paginate={"per_page": table.length}) config.configure(table) prefix = "other_" other_view = OtherQueryView(request, model=Query, table_class=OtherQueryTable) other_query_table = OtherQueryTable(other_view.get_table_data(prefix), request=request, prefix=prefix) config = RequestConfig(request, paginate={"per_page": other_query_table.length}) config.configure(other_query_table) search_data.update(other_query_table.prepare_search_data(other_view)) discrete_data.update(other_query_table.prepare_discrete_data(other_view)) terms_data.update(other_query_table.prepare_terms_data(other_view)) prefix = "user_" view = UserQueryView(request, model=Query, table_class=UserQueryTable) user_query_table = UserQueryTable(view.get_table_data(prefix), request=request, prefix=prefix) config = RequestConfig(request, paginate={"per_page": user_query_table.length}) config.configure(user_query_table) search_data.update(user_query_table.prepare_search_data(view)) discrete_data.update(user_query_table.prepare_discrete_data(view)) terms_data.update(user_query_table.prepare_terms_data(view)) template = loader.get_template("lava_results_app/query_list.html") return HttpResponse( template.render( { "user_query_table": user_query_table, "other_query_table": other_query_table, "search_data": search_data, "discrete_data": discrete_data, "terms_data": terms_data, "group_tables": group_tables, "bread_crumb_trail": BreadCrumbTrail.leading_to(query_list), "context_help": ["lava-queries-charts"], }, request=request, ))
def person_list(request): person = Person.objects.order_by('id') template = loader.get_template('persons.html') context = {"person": person} return HttpResponse(template.render(context, request))
def testjob(request, job): job = get_restricted_job(request.user, pk=job, request=request) data = ResultsView(request, model=TestSuite, table_class=ResultsTable) suite_table = ResultsTable(data.get_table_data().filter(job=job)) failed_definitions = [] yaml_dict = OrderedDict() if TestData.objects.filter(testjob=job).exists(): # some duplicates can exist, so get would fail here and [0] is quicker than try except. testdata = TestData.objects.filter(testjob=job).prefetch_related( 'actionlevels__testcase', 'actionlevels__testcase__suite')[0] if job.status in [TestJob.INCOMPLETE, TestJob.COMPLETE]: # returns something like ['singlenode-advanced', 'smoke-tests-basic', 'smoke-tests-basic'] executed = [{ case.action_metadata['test_definition_start']: case.action_metadata.get('success', '') } for case in TestCase.objects.filter( suite__in=TestSuite.objects.filter(job=job)) if case.action_metadata and 'test_definition_start' in case.action_metadata and case.suite.name == 'lava'] submitted = [ actiondata.testcase.action_metadata for actiondata in testdata.actionlevels.all() if actiondata.testcase and 'test-runscript-overlay' in actiondata.action_name ] # compare with a dict similar to created in executed for item in submitted: if executed and { item['name']: item['success'] } not in executed: comparison = {} if item['from'] != 'inline': comparison['repository'] = item['repository'] comparison['path'] = item['path'] comparison['name'] = item['name'] comparison['uuid'] = item['success'] failed_definitions.append(comparison) # hide internal python objects, like OrderedDict for data in testdata.attributes.all().order_by('name'): yaml_dict[str(data.name)] = str(data.value) RequestConfig(request, paginate={ "per_page": suite_table.length }).configure(suite_table) template = loader.get_template("lava_results_app/job.html") return HttpResponse( template.render( { 'bread_crumb_trail': BreadCrumbTrail.leading_to(testjob, job=job.id), 'job': job, 'job_link': pklink(job), 'suite_table': suite_table, 'metadata': yaml_dict, 'content_type_id': ContentType.objects.get_for_model(TestSuite).id, 'failed_definitions': failed_definitions, 'condition_choices': simplejson.dumps(QueryCondition.get_condition_choices(job)), 'available_content_types': simplejson.dumps( QueryCondition.get_similar_job_content_types()), }, request=request))
def gets(request): template = loader.get_template('users.html') context = { 'form': '', } return HttpResponse(template.render(context, request))
def gantt(request, planid): c = dict(plans=ImplementationPlan.objects.filter(id=planid)) for plan in c['plans']: plan.recompute_plan() t = loader.get_template("gantt.csv") return HttpResponse(t.render(c), content_type='text/plain')
def profile(request): if request.method == "GET": if not request.user.is_authenticated(): return HttpResponseRedirect("/login/") return render(request, "profile.html") elif request.method == "POST": if request.POST.get('connectButton'): #Get user defined values for username, password, server username = request.POST['username'] password = request.POST['password'] server = request.POST['server'] form = FileSearchForm() #initialize return message variable, userInfo variable and user folder message = "" userInfo = "" folder = dict() #make request to api p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/connect.py') ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(server + '\n') p.stdin.write(username + '\n') p.stdin.write(password + '\n') #get stdout,sterr based on timeout function stdout, stderr, returncode = timeout(p) #parse through stdout and get user datasets and versions. Also set message based on status of output if returncode != 0: message = dict({ "value": 'Error Connecting to server. Ensure that you entered the corrent server, username and password. Please try again', "type": "danger" }) else: for line in stdout.splitlines(): if username in line: datasetList = re.findall(r'dataset (.*?) version', line, re.DOTALL) dataset = "" for words in datasetList: dataset += str(words) versionList = re.findall(r'version (.*?)$', line, re.DOTALL) version = "" for words in versionList: version += str(words) if dataset in folder: folder[dataset].append(version) else: folder[dataset] = [version] userLen = len(UserInfo.objects.filter(Username=username)) if userLen == 0: userInfo = UserInfo.create(server, username, password) else: userInfo = UserInfo.objects.filter( Username=username)[0] message = dict({ 'value': 'Successfully Connected to Server', 'type': 'success' }) #set user sessions folder request.session['folder'] = folder #set user sessions information sessionInfo = dict({ "username": username, "password": password, "server": server, "solution_files": False, "connect": True }) request.session['sessionInfo'] = sessionInfo #rerender profile with information t = loader.get_template("profile.html") c = dict({ "message": message, "sessionInfo": sessionInfo, "folder": folder, 'form': form }) return HttpResponse(t.render(c, request=request)) #if a request is made to download a dataset elif request.POST.get('downloadButton'): #get session folder and user information folder = request.session.get('folder') sessionInfo = request.session.get('sessionInfo') form = FileSearchForm() #set username, password, server and dataset username = sessionInfo["username"] password = sessionInfo["password"] server = sessionInfo["server"] dataset = request.POST['dataset'] #make request to api p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/download.py') ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(server + '\n') p.stdin.write(username + '\n') p.stdin.write(password + '\n') p.stdin.write(username + '\n') p.stdin.write(dataset + '\n') #get response based on timeout function stdout, stderr, returncode = timeout(p) # set user message based on the process returncode if returncode != 0: message = dict({ "value": 'Error downloading dataset. Please try again. If the problem persists, contact support at Energy Exemplar', "type": "danger" }) else: value = "Successfully Downloaded " + dataset message = dict({"value": value, "type": "success"}) #rerender profile with information t = loader.get_template("profile.html") c = dict({ "message": message, "folder": folder, "sessionInfo": sessionInfo, 'form': form }) return HttpResponse(t.render(c, request=request)) #if request is made to launch a dataset elif request.POST.get('launchButton'): #get session folder and user information folder = request.session.get('folder') sessionInfo = request.session.get('sessionInfo') form = FileSearchForm() #set username, password, server and dataset username = sessionInfo["username"] password = sessionInfo["password"] server = sessionInfo["server"] dataset = request.POST['dataset'] version = request.POST['version'] runIndex = '' #make request to api p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/launch.py') ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(server + '\n') p.stdin.write(username + '\n') p.stdin.write(password + '\n') p.stdin.write(username + '\n') p.stdin.write(dataset + '\n') p.stdin.write('\n') p.stdin.write(version + '\n') p.stdin.write('1\n') p.stdin.write('Base\n') #get response based on timeout function stdout, stderr, returncode = timeout(p) for line in stdout.splitlines(): if 'Run' in line: runIndex = re.findall(r'Run (.*?) is complete.', line, re.DOTALL) if runIndex != '': #make request to api dp = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Solution Files/download.py') ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) dp.stdin.write(server + '\n') dp.stdin.write(username + '\n') dp.stdin.write(password + '\n') dp.stdin.write(runIndex[0] + '\n') stdout_dp, stderr_dp, returncode_dp = timeout(dp) # set user message based on the process returncode if returncode_dp != 0: message = dict({ "value": 'Error Getting Solution Files. Please try again. If the problem persists, contact support at Energy Exemplar', "type": "danger" }) else: value = "Successfully launched " + dataset message = dict({"value": value, "type": "success"}) else: message = dict({ "value": 'Error Launching dataset. Please try again. If the problem persists, contact support at Energy Exemplar', "type": "danger" }) #rerender profile with information sessionInfo["solution_files"] = True t = loader.get_template("profile.html") c = dict({ "message": message, "folder": folder, "sessionInfo": sessionInfo, 'form': form }) return HttpResponse(t.render(c, request=request)) #if request is made to launch a dataset elif request.POST.get('uploadButton'): #get session folder and user information folder = request.session.get('folder') sessionInfo = request.session.get('sessionInfo') #set username, password, server and path to file username = sessionInfo["username"] password = sessionInfo["password"] server = sessionInfo["server"] location_folder = os.path.join(BASE_DIR, 'static', 'media').replace('\\', '/') dataset = '' form = FileSearchForm(request.POST, request.FILES) if form.is_valid(): initial_obj = form.save(commit=False) initial_obj.save() location_folder += str('/' + str(initial_obj.url)) index = location_folder.rfind('/') path = location_folder[0:index + 1] dataset = location_folder[index + 1:] form.save() parseXMLResults = parseXML(location_folder) if not parseXMLResults: #make request to api p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/upload.py') ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.stdin.write(server + '\n') p.stdin.write(username + '\n') p.stdin.write(password + '\n') p.stdin.write(username + '\n') p.stdin.write(dataset + '\n') p.stdin.write(path + '\n') #get response based on timeout function stdout, stderr, returncode = timeout(p) # set user message based on the process returncode if returncode != 0: message = dict({ "value": 'Error Uploading dataset. Please try again. If the problem persists, contact support at Energy Exemplar', "type": "danger" }) else: for line in stdout.splitlines(): if "new_version" in line: folder[dataset] = re.findall( r'version (.*?)$', line, re.DOTALL) request.session['folder'] = folder value = "Successfully Loaded " + dataset message = dict({"value": value, "type": "success"}) else: message = dict({ "value": parseXMLResults, "type": "danger" }) else: # Get the validation errors of the uploaded files form_errors = "" for key, value in form.errors.iteritems(): form_errors += re.sub('<[^>]*>', '', str(value)).replace("'", "\"") message = dict({"value": form_errors, "type": "danger"}) #rerender profile with information t = loader.get_template("profile.html") c = dict({ "message": message, "folder": folder, "sessionInfo": sessionInfo, 'form': form }) return HttpResponse(t.render(c, request=request)) #if request is made to download a dataset elif request.POST.get('downloadSolutionButton'): #get session folder and user information folder = request.session.get('folder') sessionInfo = request.session.get('sessionInfo') pandas_returncode = '' squalite_returncode = '' #initalize the return message to the user message = dict({ "value": "", "type": "" }) #if the user request for a sqlite solution file if request.POST.get('sqlite_solution'): #make request to api for sqlite solution and get response p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/query_to_sqlite3.py' ) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr, squalite_returncode = timeout(p) #respond based on the returncode if squalite_returncode != 0: message[ "value"] = 'Error Downloading Solution in Sqlite Format. Please try again. If the problem persists, contact support at Energy Exemplar\n\n' else: message[ "value"] = "Successfully downloaded solution in sqlite3 format\n" #if the user request for a pandas solution file if request.POST.get('pandas_solution'): #make request to api for pandas solution and get response p = subprocess.Popen([ 'python2', os.path.join( SITE_ROOT + '../../Python-PLEXOS-API/Connect Server/query_to_pandas.py' ) ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr, pandas_returncode = timeout(p) #respond based on the returncode if pandas_returncode != 0: message[ "value"] += 'Error Downloading Solution in Pandas Format. Please try again. If the problem persists, contact support at Energy Exemplar' else: message[ "value"] += "Successfully downloaded solution in sqlite3 format" if squalite_returncode != 0 and pandas_returncode != 0: message["type"] = "success" elif squalite_returncode != 0 or pandas_returncode != 0: message["type"] = "info" else: message["type"] = "danger" #rerender profile.html with information t = loader.get_template("profile.html") c = dict({ "message": message, "folder": folder, "sessionInfo": sessionInfo }) return HttpResponse(t.render(c, request=request))