我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.template.loader.get_template()。
def add_sharing_banner(page, response): if not getattr(settings, 'WAGTAILSHARING_BANNER', True): return if hasattr(response, 'render') and callable(response.render): response.render() html = force_text(response.content) body = re.search(r'(?i)<body.*?>', html) if body: endpos = body.end() banner_template_name = 'wagtailsharing/banner.html' banner_template = loader.get_template(banner_template_name) banner_html = banner_template.render() banner_html = force_text(banner_html) content_with_banner = html[:endpos] + banner_html + html[endpos:] response.content = content_with_banner
def test_has_support_for_elapsed_time_in_template_render(settings): settings.PERFORMANCE_LIMITS = { 'Template.render': { 'time': { 'total': 0 } } } template = loader.get_template('all-group-names.markdown') with freeze_time('2016-09-29 15:52:01') as frozen_time: class SlowIterable(object): def __iter__(self): yield 'foo' frozen_time.tick(timedelta(seconds=5)) yield 'bar' with pytest.raises(LimitViolationError) as excinfo: template.render(context={'groups': SlowIterable()}) assert excinfo.value.context == {'template': ['all-group-names.markdown']}
def handler500(request, template_name='500.html'): t = get_template(template_name) tt, value, tb = sys.exc_info() ctx = Context({'exception_value': value, 'value': tt, 'tb': traceback.format_exception(tt, value, tb)}) return HttpResponseServerError(t.render(ctx))
def _send_invitation_mail(request, invitation, subject, template_name): if not invitation.invitee.email: return old_lang = translation.get_language() translation.activate(invitation.invitee.language) template = loader.get_template('groups/mail_{0}.txt'.format(template_name)) message = template.render({ 'invitation': invitation, 'site': get_current_site(request) }) translation.activate(old_lang) send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.DEFAULT_FROM_EMAIL, [invitation.invitee.email], fail_silently=True)
def send_notification_message(build_id, user_id): reset_database_connection() build = Build.objects.get(id=build_id) user = User.objects.get(id=user_id) try: log_lines = build.flows.order_by('-date_end')[0].log.split('\n') except: log_lines = build.log.split('\n') log_lines = '\n'.join(log_lines[-25:]) template_txt = get_template('build/email.txt') template_html = get_template('build/email.html') context = { 'build': build, 'log_lines': log_lines, } subject = '[{}] Build #{} of {} {} - {}'.format(build.repo.name, build.id, build.branch.name, build.plan.name, build.get_status().upper()) message = template_txt.render(Context(context)) html_message = template_html.render(Context(context)) return send_mail(subject, message, settings.FROM_EMAIL, [user.email], html_message=html_message)
def send_order_email_confirmation(sender, instance, **kwargs): """ Send email to customer with order details. """ order = instance message = get_template("emails/order_conf.html").render(Context({ 'order': order.get_serialized_data() })) mail = EmailMessage( subject="Order confirmation", body=message, from_email=EMAIL_ADMIN, to=[order.email], reply_to=[EMAIL_ADMIN], ) mail.content_subtype = "html" return mail.send()
def gen_sudo_script(role_list, sudo_list): # receive role_list = [role1, role2] sudo_list = [sudo1, sudo2] # return sudo_alias={'NETWORK': '/sbin/ifconfig, /ls'} sudo_user={'user1': ['NETWORK', 'SYSTEM']} sudo_alias = {} sudo_user = {} for sudo in sudo_list: sudo_alias[sudo.name] = sudo.commands for role in role_list: sudo_user[role.name] = ','.join(sudo_alias.keys()) sudo_j2 = get_template('jperm/role_sudo.j2') sudo_content = sudo_j2.render(Context({"sudo_alias": sudo_alias, "sudo_user": sudo_user})) sudo_file = NamedTemporaryFile(delete=False) sudo_file.write(sudo_content) sudo_file.close() return sudo_file.name
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): success_url = form.opts.get('success_url', '') delete_url = form.opts.get('delete_url', '') if delete_url: delete_url += '&' if '?' in delete_url else '?' delete_url += 'success_url=' + force_text(form.opts.get('delete_success_url', success_url)) template = get_template(form.opts.get('form_actions_template', 'ajaxviews/_form_controls.html')) btn_group = template.render({ 'delete_url': delete_url, 'success_url': force_text(success_url), 'modal_form': form.opts.get('modal_form', False), 'form_preview': form.opts.get('preview_stage', False), 'delete_confirmation': form.opts.get('delete_confirmation', False), 'form_cfg': json.dumps(form.form_cfg) if getattr(form, 'form_cfg', None) else None, }) layout_object = FormActions( Submit('save', form.opts.get('save_button_name', 'Save')), HTML(btn_group), style='margin-bottom: 0;' ) return layout_object.render(form, form_style, context)
def process_response(self, request, response): if not request.is_ajax() and not isinstance(response, HttpResponseRedirect) and hasattr(response, 'content'): content = force_text(response.content, encoding=response.charset) if '</body>' not in content: return response json_cfg = {} if hasattr(response, 'context_data'): json_cfg = response.context_data.get('json_cfg', {}) template = get_template('ajaxviews/_middleware.html') html = template.render({ 'json_cfg': json_cfg, 'main_name': settings.REQUIRE_MAIN_NAME, }) l_content, r_content = content.rsplit('</body>', 1) content = ''.join([l_content, html, '</body>', r_content]) response.content = response.make_bytes(content) if response.get('Content-Length', None): response['Content-Length'] = len(response.content) return response
def search(request): if request.method == 'GET': search_text = request.GET.get('search_text') groupname = request.session.get('user_group') hasgroup = Group.objects.get(name=groupname) print search_text print hasgroup.name filelist = File.objects.filter(Q(name__icontains=search_text)&(Q(perm__groups=hasgroup)|Q(ispublic="True"))).distinct() # filelist = File.objects.filter((Q(name=search_text)|Q(ispublic="True"))).distinct() listoffiledir=list(filelist) folderlist = {} template = loader.get_template('wxWeb/index2.html') context = Context({ 'filepath': listoffiledir, 'foldlist': folderlist, }) return HttpResponse(template.render(context))
def index(request): fileindexfolder = get_object_or_404(Folder, name="ab") # listoffiledir = [singlefile.file for singlefile in fileindexfolder.files ] hasuser = 'sclmmanager' listoffiledir = list(fileindexfolder.get_childfile_read()) can_read_folder = list(fileindexfolder.get_childfolder_read()) # can_read_folder = fileindexfolder.get_children() folderlist = [] for id in can_read_folder: fold = Folder.objects.get(id=id) folderlist.append(fold) template = loader.get_template('wxWeb/index.html') context = Context({ 'filepath':listoffiledir, 'foldlist': folderlist, }) #print template.render(context) return HttpResponse(template.render(context))
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated(): from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: template = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) response = HttpResponse(template.render({'flatpage': f}, request)) return response
def bad_request(request, exception, template_name='400.html'): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') # No exception content is passed to the template, to not disclose any sensitive information. return http.HttpResponseBadRequest(template.render()) # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}.
def render_flatpage(request, f): """ Internal interface to the flat page view. """ # If registration is required for accessing this page, and the user isn't # logged in, redirect to the login page. if f.registration_required and not request.user.is_authenticated: from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: template = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: template = loader.get_template(DEFAULT_TEMPLATE) # To avoid having to always use the "|safe" filter in flatpage templates, # mark the title and content as already safe (since they are raw HTML # content in the first place). f.title = mark_safe(f.title) f.content = mark_safe(f.content) response = HttpResponse(template.render({'flatpage': f}, request)) return response
def render(element, markup_classes): element_type = element.__class__.__name__.lower() if element_type == 'boundfield': add_input_classes(element) template = get_template("materializecssform/field.html") context = {'field': element, 'classes': markup_classes} else: has_management = getattr(element, 'management_form', None) if has_management: for form in element.forms: for field in form.visible_fields(): add_input_classes(field) template = get_template("materializecssform/formset.html") context = {'formset': element, 'classes': markup_classes} else: for field in element.visible_fields(): add_input_classes(field) template = get_template("materializecssform/form.html") context = {'form': element, 'classes': markup_classes} return template.render(context)
def schedule_list_csv(request, slug=None): schedule = fetch_schedule(slug) presentations = Presentation.objects.filter(section=schedule.section) presentations = presentations.exclude(cancelled=True).order_by("id") response = HttpResponse(mimetype="text/csv") if slug: file_slug = slug else: file_slug = "presentations" response["Content-Disposition"] = 'attachment; filename="%s.csv"' % file_slug response.write(loader.get_template("schedule/schedule_list.csv").render(Context({ "presentations": presentations, }))) return response
def render(self, name, value, attrs=None): # Prepare values attrs = self.build_attrs(attrs, name=name) if not value: value = '' options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {}) if 'options' in attrs: options = self._eval_value(attrs['options'], {}) del attrs['options'] # Render widget to HTML t = loader.get_template('markedit/ui.html') c = Context({ 'attributes': self._render_attrs(attrs), 'value': conditional_escape(force_unicode(value)), 'id': attrs['id'], 'options': options, }) return t.render(c)
def do_loadmacros(parser, token): try: tag_name, filename = token.split_contents() except IndexError: m = ("'%s' tag requires at least one argument (macro name)" % token.contents.split()[0]) raise template.TemplateSyntaxError, m if filename[0] in ('"', "'") and filename[-1] == filename[0]: filename = filename[1:-1] t = get_template(filename) macros = t.nodelist.get_nodes_by_type(DefineMacroNode) ## Metadata of each macro are stored in a new attribute ## of 'parser' class. That way we can access it later ## in the template when processing 'usemacro' tags. _setup_macros_dict(parser) for macro in macros: parser._macros[macro.name] = macro return LoadMacrosNode()
def render(self, name, value, attrs=None): if attrs is None: attrs = {} # it's called "original" because it will be replaced by a copy attrs['class'] = 'hstore-original-textarea' # get default HTML from AdminTextareaWidget html = super(BaseAdminHStoreWidget, self).render(name, value, attrs) # prepare template context template_context = Context({ 'field_name': name, 'STATIC_URL': settings.STATIC_URL, 'use_svg': django.VERSION >= (1, 9), # use svg icons if django >= 1.9 }) # get template object template = get_template('happenings/hstore_%s_widget.html' % self.admin_style) # render additional html additional_html = template.render(template_context) # append additional HTML and mark as safe html = html + additional_html html = mark_safe(html) return html
def get_learning_result(request): if request.method == 'GET': learning_form = QueryLearningForm(request.GET) if learning_form.is_valid(): cd = learning_form.cleaned_data try: train = Prediction.objects.get(step_hash=cd['stephash'], type=cd['type']) template = loader.get_template('ui/get_learning_result.html') context = { 'hit': train, } return success(template.render(context)) except Exception as e: return error(e) else: return error(str(learning_form.errors)) else: return error('Error Method.')
def show_learning_steps(request): if request.method == 'GET': if 'parent' in request.GET: if request.user.is_superuser: step_list = Protocol.objects.filter(parent=int(request.GET['parent'])).all() else: step_list = Protocol.objects.filter(parent= int(request.GET['parent'])).filter(user_id=request.user.id).all() template = loader.get_template('ui/show_learning_steps.html') context = { 'step_list': step_list, } return success(template.render(context)) else: return error('Wrong parameter.') else: return error('Method error.')
def _get_critical_checks_snippet(request, unit): """Retrieves the critical checks snippet. :param request: an `HttpRequest` object :param unit: a `Unit` instance for which critical checks need to be rendered. :return: rendered HTML snippet with the failing checks, or `None` if there are no critical failing checks. """ if not unit.has_critical_checks(): return None can_review = check_user_permission(request.user, 'review', unit.store.parent) ctx = { 'canreview': can_review, 'unit': unit, } template = loader.get_template('editor/units/xhr_checks.html') return template.render(context=ctx, request=request)
def view_error(request, analysis_type, country_abbrev, state_name, error_id): """View the error with the given error_id.""" error = models.MapError.objects.get(id=error_id) if request.POST: if request.GET.get('flag_error'): error.flagged_count += 1 error.save() context = { 'center': ((error.ne_lon + error.sw_lon) / 2, (error.ne_lat + error.sw_lat) / 2), 'error': error, 'country_abbrev': country_abbrev, 'state_title': state_name.replace('-', ' ').title(), 'state_name': state_name, 'analysis_title': analysis_type.replace('-', ' ').title(), 'analysis_type': analysis_type } template = loader.get_template('view_error.html') return HttpResponse(template.render(context, request))
def inclusion_tag(file_name, context_class=Context, takes_context=False): def wrap(func): @functools.wraps(func) def method(self, context, nodes, *arg, **kwargs): _dict = func(self, context, nodes, *arg, **kwargs) from django.template.loader import get_template, select_template if isinstance(file_name, Template): t = file_name elif not isinstance(file_name, basestring) and is_iterable(file_name): t = select_template(file_name) else: t = get_template(file_name) _dict['autoescape'] = context.autoescape _dict['use_l10n'] = context.use_l10n _dict['use_tz'] = context.use_tz _dict['admin_view'] = context['admin_view'] csrf_token = context.get('csrf_token', None) if csrf_token is not None: _dict['csrf_token'] = csrf_token nodes.append(t.render(_dict)) return method return wrap
def hijack_field(self, obj): hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES if 'user_id' in hijack_attributes: hijack_url = reverse('hijack:login_with_id', args=(obj.pk, )) elif 'email' in hijack_attributes: hijack_url = reverse('hijack:login_with_email', args=(obj.email, )) else: hijack_url = reverse('hijack:login_with_username', args=(obj.username, )) button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE) button_context = { 'hijack_url': hijack_url, 'username': str(obj), } if VERSION < (1, 8): button_context = Context(button_context) return button_template.render(button_context)
def send_email_ticket_confirm(request, payment_info): """ :param request Django request object :param payment_info Registration object """ mail_title = u"PyCon APAC 2016 ???? ??(Registration confirmation)" product = Product() variables = Context({ 'request': request, 'payment_info': payment_info, 'amount': product.price }) html = get_template('mail/ticket_registered_html.html').render(variables) text = get_template('mail/ticket_registered_text.html').render(variables) msg = EmailMultiAlternatives( mail_title, text, settings.EMAIL_SENDER, [payment_info.email]) msg.attach_alternative(html, "text/html") msg.send(fail_silently=False)
def log_tests(request): es = get_elastic() if not es: return HttpResponse('not able to connect to elasticsearch') res = es.search(index="message-log", doc_type='message', body={ "size": 0, "aggs" : { "test_ids" : { "terms" : { "field" : "test_id", "size" : 500 } } }}) test_ids = [] for bucket in res['aggregations']['test_ids']['buckets']: test_id = bucket['key'] test_ids.append({'id':'test_id_'+test_id, 'name':test_id}) context = { 'groups' : test_ids } template = loader.get_template('golem/log.html') return HttpResponse(template.render(context,request))
def pdfPG(request, nrop): if not request.session['nropreinscripto'] == nrop: return HttpResponse("ERROR AL GENERAR EL COMPROBANTE") template = get_template('pg/pg/comprobante.html') postulante = Postulante.objects.get(pg__nro_de_preinscripto=nrop) contexto = {'postulante' : postulante } pdf = render_to_pdf('pg/pg/comprobante.html', contexto) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Comprobante_Preinscripcion" content = "inline; filename='%s'" % (filename) return response return HttpResponse("ERROR AL GENERAR EL COMPROBANTE") #### #listado de todas las preinscripciones
def admin_pg_cc(request, nrop): template = get_template('pg/adminpg/comprobante_confirmado.html') preinscripcion = PreinscripcionGeneral.objects.get(nro_de_preinscripto=nrop) user = preinscripcion.usuarioqueconfirma contexto = {'preinscripcion' : preinscripcion, 'user': user } pdf = render_to_pdf('pg/adminpg/comprobante_confirmado.html', contexto) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Comprobante_Preinscripcion" content = "inline; filename='%s'" % (filename) #download = request.GET.get("download") #return response #if download: # content = "attachment; filename='%s'" % (filename) #response['Content-Disposition'] = content return response return HttpResponse("ERROR AL GENERAR EL COMPROBANTE") ####
def test_wkhtmltopdf(self): """Should run wkhtmltopdf to generate a PDF""" title = 'A test template.' template = loader.get_template('sample.html') temp_file = render_to_temporary_file(template, context={'title': title}) try: # Standard call pdf_output = wkhtmltopdf(pages=[temp_file.name]) self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output) # Single page pdf_output = wkhtmltopdf(pages=temp_file.name) self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output) # Unicode pdf_output = wkhtmltopdf(pages=[temp_file.name], title=u'?') self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output) # Invalid arguments self.assertRaises(CalledProcessError, wkhtmltopdf, pages=[]) finally: temp_file.close()
def render_field(self, field, parent_style): if isinstance(field._field, serializers.HiddenField): return '' style = dict(self.default_style[field]) style.update(field.style) if 'template_pack' not in style: style['template_pack'] = parent_style.get('template_pack', self.template_pack) style['renderer'] = self # Get a clone of the field with text-only value representation. field = field.as_form_field() if style.get('input_type') == 'datetime-local' and isinstance(field.value, six.text_type): field.value = field.value.rstrip('Z') if 'template' in style: template_name = style['template'] else: template_name = style['template_pack'].strip('/') + '/' + style['base_template'] template = loader.get_template(template_name) context = {'field': field, 'style': style} return template_render(template, context)
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render serializer data and return an HTML form, as a string. """ renderer_context = renderer_context or {} form = data.serializer style = renderer_context.get('style', {}) if 'template_pack' not in style: style['template_pack'] = self.template_pack style['renderer'] = self template_pack = style['template_pack'].strip('/') template_name = template_pack + '/' + self.base_template template = loader.get_template(template_name) context = { 'form': form, 'style': style } return template_render(template, context)
def send_summary(report_pk): report = Report.objects.get(pk=report_pk) daily = report.get_daily() messages = [] questions = daily.report.question_set.active() surveys = daily.survey_set.all() for user in report.stakeholders: context = Context({'user': user, 'daily': daily, 'surveys': surveys, 'questions': questions}) context['SITE_URL'] = settings.SITE_URL subject = render_to_string('email/summary_subject.txt', context) text = get_template('email/summary.txt') html = get_template('email/summary.html') text_content = text.render(context) html_content = html.render(context) messages.append([subject, text_content, html_content, settings.DEFAULT_FROM_EMAIL, [user.email]]) send_mass_html_mail(messages) daily.summary_submitted = now() daily.save()
def input_form(request): """ Course Addition Tool Endpoints """ if not request.user.is_authenticated(): return HttpResponseRedirect('/admin/login/?next=%s' % request.path) VC1 = VEDACat() VC1.institution_list() inst_list = json.dumps(VC1.inst_list) template = loader.get_template('course_form.html') context = RequestContext(request, ({ 'institution_list': inst_list })) return HttpResponse(template.render(context))
def do_loadmacros(parser, token): try: tag_name, filename = token.split_contents() except IndexError: m = ("'%s' tag requires at least one argument (macro name)" % token.contents.split()[0]) raise template.TemplateSyntaxError(m) if filename[0] in ('"', "'") and filename[-1] == filename[0]: filename = filename[1:-1] t = get_template(filename) macros = t.nodelist.get_nodes_by_type(DefineMacroNode) ## Metadata of each macro are stored in a new attribute ## of 'parser' class. That way we can access it later ## in the template when processing 'usemacro' tags. _setup_macros_dict(parser) for macro in macros: parser._macros[macro.name] = macro return LoadMacrosNode()
def index(request): indices = ES_Manager.get_indices() template = loader.get_template('account.html') ds = Datasets().activate_dataset(request.session) datasets = sort_datasets(ds.get_datasets(),indices) datasets = get_allowed_datasets(datasets, request.user) # TODO: We should check if the model is actually present on the disk sem_models = ModelRun.objects.all().filter(run_status='completed').order_by('-pk') try: request.session['model'] except KeyError: if len(sem_models): request.session['model'] = str(sem_models[0].id) return HttpResponse(template.render({'STATIC_URL':STATIC_URL, 'datasets':datasets,'models':sem_models},request))
def index(request): # Define selected mapping ds = Datasets().activate_dataset(request.session) dataset = ds.get_index() mapping = ds.get_mapping() es_m = ds.build_manager(ES_Manager) fields = get_fields(es_m) searches = [{'id':search.pk,'desc':search.description} for search in Search.objects.filter(author=request.user, dataset__index=dataset, dataset__mapping=mapping)] template = loader.get_template('grammar_builder.html') return HttpResponse(template.render({'STATIC_URL':STATIC_URL, 'searches':searches, 'features':fields},request))
def get_table(request): polarity = request.GET['polarity'] if request.GET['is_test'] == 'true': inclusive_test_grammar = json.loads(request.GET['inclusive_test_grammar']) #exclusive_test_grammar = json.loads(request.GET['exclusive_test_grammar']) layers = ['id'] + sorted(extract_layers(inclusive_test_grammar)) else: inclusive_id = int(request.GET['inclusive_grammar_id']) exclusive_id = int(request.GET['exclusive_grammar_id']) inclusive_metaquery = generate_metaquery_dict(inclusive_id, request.user, component={}) exclusive_metaquery = generate_metaquery_dict(exclusive_id, request.user, component={}) layers = ['id'] + sorted(extract_layers(inclusive_metaquery) | extract_layers(exclusive_metaquery)) template = loader.get_template('grammar_builder_table.html') return HttpResponse(template.render({'features':layers, 'polarity':polarity},request))
def index(request): template = loader.get_template('mwe_miner.html') lexicons = [] runs = [] for run in Run.objects.all().filter(user=request.user).order_by('-pk'): try: groups = json.loads(run.results).values() num_mwes = sum(len(group['mwes']) for group in groups) setattr(run,'num_groups',len(groups)) setattr(run,'num_mwes',num_mwes) # setattr(run,'committed',len({approved_candidate.candidate for approved_candidate in approved_term_candidates} & {committed_candidate.term for committed_candidate in Term.objects.filter(author=request.user)})) except ValueError as e: print 'Exception', e pass runs.append(run) for lexicon in Lexicon.objects.all().filter(author=request.user): setattr(lexicon,'size',Word.objects.all().filter(lexicon=lexicon.id).count()) lexicons.append(lexicon) # Define selected mapping ds = Datasets().activate_dataset(request.session) es_m = ds.build_manager(ES_Manager) fields = es_m.get_column_names() return HttpResponse(template.render({'lexicons':lexicons,'STATIC_URL':STATIC_URL,'runs':runs,'fields':fields},request))
def cluster_query(request): params = request.POST ds = Datasets().activate_dataset(request.session) es_m = ds.build_manager(ES_Manager) es_m.build(params) cluster_m = ClusterManager(es_m,params) clustering_data = convert_clustering_data(cluster_m) template_params = {'STATIC_URL': STATIC_URL, 'URL_PREFIX': URL_PREFIX, 'clusters': clustering_data} template = loader.get_template('cluster_results.html') return HttpResponse(template.render(template_params, request))
def import_supervisors(request): # configure template csv = create_temp_copy(request.FILES['datafile'].temporary_file_path()) enc = get_variable(request, 'encoding') email = get_variable(request, 'email_notification') write_last_parameter(request.user, 'dbbackend.database_supervisors.email', email) if len(email) == 0: email = None t = threading.Thread(target=dbimport.queue_import_supervisors, args=(csv, enc), kwargs={'email': email}) t.setDaemon(True) t.start() template = loader.get_template('message.html') context = applist.template_context() context['message'] = "Started import of supervisors... Check 'Table status' page for progress." context['back_link'] = "/dbbackend/tablestatus" context['back_text'] = "Table status" return HttpResponse(template.render(context, request))
def import_scholarships(request): # configure template csv = create_temp_copy(request.FILES['datafile'].temporary_file_path()) enc = get_variable(request, 'encoding') email = get_variable(request, 'email_notification') write_last_parameter(request.user, 'dbbackend.database_scholarships.email', email) if len(email) == 0: email = None t = threading.Thread(target=dbimport.queue_import_scholarships, args=(csv, enc), kwargs={'email': email}) t.setDaemon(True) t.start() template = loader.get_template('message.html') context = applist.template_context() context['message'] = "Started import of scholarships... Check 'Table status' page for progress." context['back_link'] = "/dbbackend/tablestatus" context['back_text'] = "Table status" return HttpResponse(template.render(context, request))
def import_associatedrole(request): # configure template csv = create_temp_copy(request.FILES['datafile'].temporary_file_path()) enc = get_variable(request, 'encoding') email = get_variable(request, 'email_notification') write_last_parameter(request.user, 'dbbackend.database_associatedrole.email', email) if len(email) == 0: email = None t = threading.Thread(target=dbimport.queue_import_associatedrole, args=(csv, enc), kwargs={'email': email}) t.setDaemon(True) t.start() template = loader.get_template('message.html') context = applist.template_context() context['message'] = "Started import of associate role... Check 'Table status' page for progress." context['back_link'] = "/dbbackend/tablestatus" context['back_text'] = "Table status" return HttpResponse(template.render(context, request))
def import_coursedefs(request): # configure template csv = create_temp_copy(request.FILES['datafile'].temporary_file_path()) year = int(get_variable(request, 'year', def_value='1900')) enc = get_variable(request, 'encoding') email = get_variable(request, 'email_notification') write_last_parameter(request.user, 'dbbackend.database_coursedefs.email', email) if len(email) == 0: email = None t = threading.Thread(target=dbimport.queue_import_coursedefs, args=(year, csv, enc), kwargs={'email': email}) t.setDaemon(True) t.start() template = loader.get_template('message.html') context = applist.template_context() context['message'] = "Started import of course definitions... Check 'Table status' page for progress." context['back_link'] = "/dbbackend/tablestatus" context['back_text'] = "Table status" return HttpResponse(template.render(context, request))
def import_bulk(request): # configure template csv = request.FILES['datafile'].temporary_file_path() email = get_variable(request, 'email_notification') write_last_parameter(request.user, 'dbbackend.database_bulk.email', email) if len(email) == 0: email = None msg = dbimport.import_bulk(csv, email) template = loader.get_template('message.html') context = applist.template_context() if msg is None: context['message'] = "Successful bulk import!" else: context['message'] = "Failed to bulk import: " + msg context['back_link'] = "/" context['back_text'] = "Start" return HttpResponse(template.render(context, request))
def search_by_paper(request): # get parameters response, paper = get_variable_with_error(request, 'supervisors', 'paper', as_list=False) if response is not None: return response # get year from earliest start date max_years = get_max_years() # configure template template = loader.get_template('supervisors/search_by_paper.html') context = applist.template_context('supervisors') context['papers'] = get_papers(paper) context['max_years'] = int(max_years) if max_years is not None else YEARS_BACK context['scholarships'] = get_scholarships() context['last_programs'] = read_last_parameter(request.user, 'supervisors.search_by_paper.programs', PROGRAM_TYPES) context['last_supervisor_type'] = read_last_parameter(request.user, 'supervisors.search_by_paper.supervisor_type', SUPERVISOR_TYPES) context['last_study_type'] = read_last_parameter(request.user, 'supervisors.search_by_paper.study_type', STUDY_TYPES) context['last_only_current'] = read_last_parameter(request.user, 'supervisors.search_by_paper.only_current', True) context['last_min_months'] = read_last_parameter(request.user, 'supervisors.search_by_paper.min_months', -1) context['last_scholarship'] = read_last_parameter(request.user, 'supervisors.search_by_paper.scholarship', DEFAULT_SCHOLARSHIP) context['last_sort_column'] = read_last_parameter(request.user, 'supervisors.search_by_paper.sort_column', "supervisor") context['last_sort_order'] = read_last_parameter(request.user, 'supervisors.search_by_paper.sort_order', "asc") return HttpResponse(template.render(context, request))