我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.template.Context()。
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 bootstrap_formset_errors(*args, **kwargs): """ Render formset errors **Tag name**:: bootstrap_formset_errors **Parameters**: formset The formset that is being rendered layout Context value that is available in the template ``bootstrap4/form_errors.html`` as ``layout``. **Usage**:: {% bootstrap_formset_errors formset %} **Example**:: {% bootstrap_formset_errors formset layout='inline' %} """ return render_formset_errors(*args, **kwargs)
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 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 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 permission_denied(request, exception, template_name='403.html'): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c))
def default_urlconf(request): "Create an empty URLconf 404 error response." t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE) c = Context({ "title": _("Welcome to Django"), "heading": _("It worked!"), "subheading": _("Congratulations on your first Django-powered page."), "instructions": _("Of course, you haven't actually done any work yet. " "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."), "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your " "Django settings file and you haven't configured any URLs. Get to work!"), }) return HttpResponse(t.render(c), content_type='text/html') # # Templates are embedded in the file so that we know the error handler will # always work even if the template loader is broken. #
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 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(self, request, object_id): model_fields = [f.name for f in self.opts.fields] fields = [f for f in request.GET['fields'].split(',') if f in model_fields] defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_class = modelform_factory(self.model, **defaults) form = form_class(instance=self.org_obj) helper = FormHelper() helper.form_tag = False helper.include_media = False form.helper = helper s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \ '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>' t = template.Template(s) c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)}) return HttpResponse(t.render(c))
def test_simple(self): tpl = Template(""" <div class="echoices"> {{ echoices }} </div> <div class="echoices.FIELD1"> {{ echoices.FIELD1 }} </div> <div class="echoices.FIELD1.value"> {{ echoices.FIELD1.value }} </div> <div class="echoices.FIELD1.label"> {{ echoices.FIELD1.label }} </div> """) ctx = Context(dict(echoices=ETestCharChoices)) rendered = tpl.render(ctx) rendered = str(rendered.strip()) self.assertIn(ETestCharChoices.FIELD1.name, rendered) self.assertIn(ETestCharChoices.FIELD1.value, rendered) self.assertIn(ETestCharChoices.FIELD1.label, rendered)
def test_iteration(self): tpl = Template(""" {% for e in echoices %} <div class="e"> {{ e }} </div> <div class="e.value"> {{ e.value }} </div> <div class="e.label"> {{ e.label }} </div> {% endfor %} """) ctx = Context(dict(echoices=ETestCharChoices)) rendered = tpl.render(ctx) rendered = str(rendered.strip()) for e in ETestCharChoices: self.assertIn(e.name, rendered) self.assertIn(e.value, rendered) self.assertIn(e.label, rendered)
def django_render_block(template, block_name, context): # Create a Django Context. context_instance = Context(context) # Get the underlying django.template.base.Template object. template = template.template # Bind the template to the context. with context_instance.bind_template(template): # Before trying to render the template, we need to traverse the tree of # parent templates and find all blocks in them. parent_template = _build_block_context(template, context_instance) try: return _render_template_block(template, block_name, context_instance) except BlockNotFound: # The block wasn't found in the current template. # If there's no parent template (i.e. no ExtendsNode), re-raise. if not parent_template: raise # Check the parent template for this block. return _render_template_block( parent_template, block_name, context_instance)
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 raise_no_permission_exception(self, instance=None): from django.template import Context, Template t = Template(""" <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> No permission to perform this action {% if instance %} <br/> <a href="{% url 'wf_detail' instance.pk %}"> View this process </a> {% endif %} </body> </html> """) http_response = HttpResponse( t.render(Context({"instance": instance})), content_type='text/html', status=403) raise HttpResponseException(http_response)
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_mass_contact_email(ticket, email_subject, email_body): template = loader.get_template_from_string(email_subject) context = Context({ 'publicId': ticket.publicId, 'service': ticket.service.name.replace('.', '[.]'), 'lang': ticket.defendant.details.lang, }) subject = template.render(context) template = loader.get_template_from_string(email_body) context = Context({ 'publicId': ticket.publicId, 'service': ticket.service.name.replace('.', '[.]'), 'lang': ticket.defendant.details.lang, }) body = template.render(context) implementations.instance.get_singleton_of('MailerServiceBase').send_email( ticket, ticket.defendant.details.email, subject, body, 'MassContact', )
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 template_render(template, context=None, request=None): """ Passing Context or RequestContext to Template.render is deprecated in 1.9+, see https://github.com/django/django/pull/3883 and https://github.com/django/django/blob/1.9/django/template/backends/django.py#L82-L84 :param template: Template instance :param context: dict :param request: Request instance :return: rendered template as SafeText instance """ if isinstance(template, Template): if request: context = RequestContext(request, context) else: context = Context(context) return template.render(context) # backends template, e.g. django.template.backends.django.Template else: return template.render(context, request=request)
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 test_template(self): # prepare a base template using the default engine template = Template("Hello {{name}}!") ctx = Context({'name': 'Django'}) # (trace) the template rendering start = time.time() eq_(template.render(ctx), 'Hello Django!') end = time.time() # tests spans = self.tracer.writer.pop() assert spans, spans eq_(len(spans), 1) span = spans[0] eq_(span.span_type, 'template') eq_(span.name, 'django.template') eq_(span.get_tag('django.template_name'), 'unknown') assert start < span.start < span.start + span.duration < end
def test_render_recursetree(db): a = MyTree.objects.create(label='a') MyTree.objects.create(label='ab', parent=a) t = Template( "{% load mpathy %}{% recursetree nodes %}" "{% for node in nodes %}\n" " <li>{{ node.label }}<ul>{% recurse node.get_children %}</ul></li>" "{% endfor %}" "{% endrecursetree %}" ) context = Context({ 'nodes': MyTree.objects.all(), }) rendered = t.render(context) assert rendered == ( '\n' ' <li>a<ul>\n' ' <li>ab<ul></ul></li></ul></li>' )
def build_messages(self, data): """ Build email and SMS messages using the custom templates and webhook data. """ messages = {} if self.text_message: messages['text'] = Template(self.text_message).render(Context(data)) if self.html_message: messages['html'] = Template(self.html_message).render(Context(data)) if self.sms_message: messages['sms'] = Template(self.sms_message).render(Context(data)) return messages
def scheduleSandboxDeployment(request, sbr): """ Given a newly created sandbox request, schedule the deployment with the backend. This will also handle any quota checking, notifications, and environment specific prep. """ if sbr.sandbox.playground.environment == 'locl': # local deploy, no formal request sbr.request_status = 'avl' sbr.save() else: # environment deploy, let's kick it to the admins sandbox_request_uri = request.build_absolute_uri(reverse('admin:cocreate_sandboxrequest_change', args=(sbr.id,))) mail_admins( "Sandbox Request for Review", "There's a new request for review at " + sandbox_request_uri, html_message = get_template("sandboxRequestToAdmins.html").render(Context({"sandbox_request_uri": sandbox_request_uri})) )
def instructions(request): if request.user.is_authenticated() and request.user.is_turker: # Has the user passed the initial test yet? if len(QuizHistory.objects.filter(user=request.user,correct=True)) == 0: return HttpResponseRedirect("/webapp/rules") record = InstructionView() record.user = request.user record.date_time = timezone.now() record.save() return render(request,"turk_instructions_2.html", Context(_getPaymentContext())) record = InstructionView() record.user = request.user record.date_time = timezone.now() record.save() return render(request, "turk_instructions_2.html")
def orchidExistingPlayer(request): if request.user.is_authenticated(): logout(request) users = EVUser.objects.filter(experiment__experiment_name=ORCHID_SHOWCASE) if request.method == "GET": users = sorted(users,key=lambda user:user.username) return render(request,"orchid_existing_player.html", Context({"users" : users})) else: if "user" in request.POST: username = request.POST["user"] try: user = authenticate(username=username,password=ORCHID_PASSWORD) login(request, user) return HttpResponseRedirect ("/webapp/home/") except: return render(request,"orchid_existing_player.html", Context({"users" : users,"error_message" : "Something went wrong. Try again."})) else: return render(request,"orchid_existing_player.html", Context({"users" : users,"error_message" : "Please select a user."}))
def orchidNewGame(request): previousBest = request.user.best_monthly_score profit = request.user.balance - request.user.treatment.user_initial_balance game = request.user.current_day / request.user.treatment.getNumberOfDays() if profit > previousBest or game == 1: request.user.best_monthly_score = profit c = Context({"new_best" : profit, "game":game }) else: c = Context({"old_best" : previousBest,"profit" : profit, "game":game }) request.user.energy_units = request.user.treatment.user_initial_energy_units request.user.balance = request.user.treatment.user_initial_balance request.user.save() return render(request, "reset_page_orchid.html",c)
def page_not_found(request, template_name='404.html'): context = { 'request_path': request.path, 'error': { 'title': _('Page not found'), 'message': _("We tried but couldn't find this page, sorry."), }, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return HttpResponseNotFound(body, content_type=content_type)
def render(self, name, value, attrs=None): if value is None: value = "" if VERSION < (1, 11): final_attrs = self.build_attrs(attrs, name=name) else: final_attrs = self.build_attrs(attrs, {'name': name}) if "class" not in final_attrs: final_attrs["class"] = "" final_attrs["class"] += " wmd-input" template = loader.get_template(self.template) # Compatibility fix: # see https://github.com/timmyomahony/django-pagedown/issues/42 context = { "attrs": flatatt(final_attrs), "body": conditional_escape(force_unicode(value)), "id": final_attrs["id"], "show_preview": self.show_preview, } context = Context(context) if VERSION < (1, 9) else context return template.render(context)
def get_context_data(self,**kwargs): context = super(GiftCertificatePDFView,self).get_context_data(**kwargs) template = getConstant('vouchers__giftCertPDFTemplate') # For security reasons, the following tags are removed from the template before parsing: # {% extends %}{% load %}{% debug %}{% include %}{% ssi %} content = re.sub('\{%\s*((extends)|(load)|(debug)|(include)|(ssi))\s+.*?\s*%\}','',template.content) t = Template(content) rendered_content = t.render(Context(context)) context.update({ 'header': template.subject, 'content': rendered_content }) return context
def template_render(template, context=None, request=None): """ Passing Context or RequestContext to Template.render is deprecated in 1.9+, see https://github.com/django/django/pull/3883 and https://github.com/django/django/blob/1.9rc1/django/template/backends/django.py#L82-L84 :param template: Template instance :param context: dict :param request: Request instance :return: rendered template as SafeText instance """ if django.VERSION < (1, 8) or isinstance(template, Template): if request: context = RequestContext(request, context) else: context = Context(context) return template.render(context) # backends template, e.g. django.template.backends.django.Template else: return template.render(context, request=request)
def get_dynamic_desc(self, language): if language == "en": template = Template(self.description_en) else: template = Template(self.description_de) context = Context({ "advisor": self.advisor, "afterparty_location": self.afterparty_time, "afterparty_time": self.afterparty_time, "appetizer_time": self.appetizer_time, "event_date": self.date, "dessert_time": self.dessert_time, "end_registration": self.end_registration, "event_name": self.name, "event_semester": self.semester, "main_course_time": self.main_course_time, }) dyn_desc = template.render(context) return dyn_desc
def site_email(to, template, context, subject): template = template subject = subject to = to from_email = settings.SENDER_EMAIL #context = Context(context) html_message = get_template('emails/' + template + '.html').render(context) message = strip_tags(html_message) send_mail( subject=subject, message=message, from_email=from_email, recipient_list=to, html_message=html_message )
def render_string(self, template_name, **kwargs): #template_path = self.get_template_path() #if not template_path: #frame = sys._getframe(0) #web_file = frame.f_code.co_filename #while frame.f_code.co_filename == web_file: #frame = frame.f_back #template_path = os.path.dirname(frame.f_code.co_filename) #with RequestHandler._template_loader_lock: #if template_path not in RequestHandler._template_loaders: #loader = self.create_template_loader(template_path) #RequestHandler._template_loaders[template_path] = loader #else: #loader = RequestHandler._template_loaders[template_path] #t = loader.load(template_name) #namespace = self.get_template_namespace() #namespace.update(kwargs) #return t.generate(**namespace) with io.open(template_name, mode='r',encoding='UTF-8') as f: html = f.read() template_strings = Template(html) return template_strings.render(context=Context(dict_=kwargs))
def create_from_inquiry(self, inquiry, recipient, data): exists = InquiryRequest.objects.filter(inquiry=inquiry, recipient=recipient).exists() if exists: return slug = self.get_random_unique_slug() ir = InquiryRequest( slug=slug, inquiry=inquiry, recipient=recipient, ) template = inquiry.template context = self.make_context(ir, template, data) template_context = Context(context) ir.from_email = template.get_from_email(template_context) ir.subject = template.get_subject(template_context) ir.body = template.get_body(template_context) ir.intro = template.get_intro(template_context) ir.context = context ir.save() return ir