我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用django.template.context.Context()。
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 submit_row(context): """ Displays the row of buttons for delete and save. """ change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) ctx = Context(context) ctx.update({ 'show_delete_link': ( not is_popup and context['has_delete_permission'] and change and context.get('show_delete', True) ), 'show_save_as_new': not is_popup and change and save_as, 'show_save_and_add_another': ( context['has_add_permission'] and not is_popup and (not save_as or context['add']) ), 'show_save_and_continue': not is_popup and context['has_change_permission'] and show_save_and_continue, 'show_save': show_save, }) return ctx
def _render(self, context): """ Renders the plain and html versions of a template. Return both in a tuple, where the first element is the plain text version and the second element is the html version :return: (str, str,) """ if not context: context = Context({}) plain = self.template_plain.render(context) html = self.template_html.render(context) css = get_template(self.template_style).render(Context({})) p = Pynliner() html = p.from_string(html).with_cssString(css).run() return plain, html
def handler404(request, template_name='404.html'): t = get_template(template_name) ctx = Context({}) return HttpResponseNotFound(t.render(ctx))
def render(self, context=None, request=None): # A deprecation path is required here to cover the following usage: # >>> from django.template import Context # >>> from django.template.loader import get_template # >>> template = get_template('hello.html') # >>> template.render(Context({'name': 'world'})) # In Django 1.7 get_template() returned a django.template.Template. # In Django 1.8 it returns a django.template.backends.django.Template. # In Django 1.10 the isinstance checks should be removed. If passing a # Context or a RequestContext works by accident, it won't be an issue # per se, but it won't be officially supported either. if isinstance(context, RequestContext): if request is not None and request is not context.request: raise ValueError( "render() was called with a RequestContext and a request " "argument which refer to different requests. Make sure " "that the context argument is a dict or at least that " "the two arguments refer to the same request.") warnings.warn( "render() must be called with a dict, not a RequestContext.", RemovedInDjango110Warning, stacklevel=2) elif isinstance(context, Context): warnings.warn( "render() must be called with a dict, not a Context.", RemovedInDjango110Warning, stacklevel=2) else: context = make_context(context, request) try: return self.template.render(context) except TemplateDoesNotExist as exc: reraise(exc, self.backend)
def render_form(self, step, form): template = get_template(self.templates.get(step, 'testapp/default_form.html')) context = Context() context['form'] = form return template.render(context)
def render_to_temporary_file(template, context, request=None, mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True): if django.VERSION < (1, 8): # If using a version of Django prior to 1.8, ensure ``context`` is an # instance of ``Context`` if not isinstance(context, Context): if request: context = RequestContext(request, context) else: context = Context(context) content = template.render(context) else: content = template.render(context, request) content = smart_text(content) content = make_absolute_paths(content) try: # Python3 has 'buffering' arg instead of 'bufsize' tempfile = NamedTemporaryFile(mode=mode, buffering=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) except TypeError: tempfile = NamedTemporaryFile(mode=mode, bufsize=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) try: tempfile.write(content.encode('utf-8')) tempfile.flush() return tempfile except: # Clean-up tempfile if an Exception is raised. tempfile.close() raise
def assertFooter(self, context, output, template='{% admin_footer %}'): """ :param template: :param context: :param output: """ template = base.Template('{% load footer %}' + template) ctx = Context(context) self.assertEqual(template.render(ctx), output)
def assertNavigation(self, context, output, template='{% admin_navigation %}'): """ Ensure rendered template is correct. :param template: :param context: :param output: """ template = base.Template('{% load navigation %}' + template) ctx = Context(context) self.assertEqual(template.render(ctx), output)
def _build_context(self, **kwargs): """ Must return an instance of django.template.context.Context with the template variables set for each implementation :return: None """ # adding full url to logo kwargs.update({ 'logo_url': "{}vaultier/images/logo-email.png".format( urljoin(settings.SITE_URL, settings.STATIC_URL)) }) return Context(kwargs)
def __str__(self): tpl = get_template(self.template) return mark_safe(tpl.render(Context(self.get_context())))
def render_blocks(context, block_context, parent=None, template=None, **kwargs): if isinstance(block_context, basestring): try: app_label, model_name = block_context.split('.') block_context = apps.get_model(app_label, model_name) except ValueError: error = ('First argument to render_blocks must be the block context ' ' model, or string in the format "app_label.ModelName"') raise TemplateSyntaxError(error) if not issubclass(block_context, BlockContext): error = ('block_context must be a clubhouse.core.models.BlockContext ' 'instance') raise TemplateSyntaxError(error) if not parent: try: parent = context['page'].get_content_model() except KeyError: error = ('Could not find parent for block context, please provide') raise TemplateSyntaxError(error) if not template: template = block_context.get_template() parent_ct = ContentType.objects.get_for_model(parent) parent_id = parent.pk kwargs.update({ 'blocks': block_context.objects.filter(parent_type=parent_ct, parent_id=parent_id).order_by('order'), 'parent': parent, 'context_model': block_context }) return select_template([template, 'block_context.html'])\ .render(Context(kwargs))
def get_context(self, path=None, page=None): if not path: path = self.get_pages_root() context = {} request = self.get_request(path, page=page) context['request'] = request return Context(context)
def admin_list_filter(cl, spec): tpl = get_template(spec.template) return tpl.render(Context({ 'title': spec.title, 'choices' : list(spec.choices(cl)), 'spec': spec, }))
def render(self, context=None, request=None): # A deprecation path is required here to cover the following usage: # >>> from django.template import Context # >>> from django.template.loader import get_template # >>> template = get_template('hello.html') # >>> template.render(Context({'name': 'world'})) # In Django 1.7 get_template() returned a django.template.Template. # In Django 1.8 it returns a django.template.backends.django.Template. # In Django 2.0 the isinstance checks should be removed. If passing a # Context or a RequestContext works by accident, it won't be an issue # per se, but it won't be officially supported either. if isinstance(context, RequestContext): if request is not None and request is not context.request: raise ValueError( "render() was called with a RequestContext and a request " "argument which refer to different requests. Make sure " "that the context argument is a dict or at least that " "the two arguments refer to the same request.") warnings.warn( "render() must be called with a dict, not a RequestContext.", RemovedInDjango20Warning, stacklevel=2) elif isinstance(context, Context): warnings.warn( "render() must be called with a dict, not a Context.", RemovedInDjango20Warning, stacklevel=2) else: context = make_context(context, request) return self.template.render(context)
def add_service(request, username, id_string): data = {} form = RestServiceForm() xform = get_object_or_404( XForm, user__username__iexact=username, id_string__exact=id_string) if request.method == 'POST': form = RestServiceForm(request.POST) restservice = None if form.is_valid(): service_name = form.cleaned_data['service_name'] service_url = form.cleaned_data['service_url'] try: rs = RestService(service_url=service_url, name=service_name, xform=xform) rs.save() except IntegrityError: message = _(u"Service already defined.") status = 'fail' else: status = 'success' message = (_(u"Successfully added service %(name)s.") % {'name': service_name}) service_tpl = render_to_string("service.html", { "sv": rs, "username": xform.user.username, "id_string": xform.id_string}) restservice = service_tpl else: status = 'fail' message = _(u"Please fill in all required fields") if form.errors: for field in form: message += Template(u"{{ field.errors }}")\ .render(Context({'field': field})) if request.is_ajax(): response = {'status': status, 'message': message} if restservice: response["restservice"] = u"%s" % restservice return HttpResponse(json.dumps(response)) data['status'] = status data['message'] = message data['list_services'] = RestService.objects.filter(xform=xform) data['form'] = form data['username'] = username data['id_string'] = id_string return render(request, "add-service.html", data)
def add_service(request, username, id_string): data = {} form = RestServiceForm() xform = get_object_or_404( XForm, user__username__iexact=username, id_string__iexact=id_string) if request.method == 'POST': form = RestServiceForm(request.POST) restservice = None if form.is_valid(): service_name = form.cleaned_data['service_name'] service_url = form.cleaned_data['service_url'] try: rs = RestService(service_url=service_url, name=service_name, xform=xform) rs.save() except IntegrityError: message = _(u"Service already defined.") status = 'fail' else: status = 'success' message = (_(u"Successfully added service %(name)s.") % {'name': service_name}) service_tpl = render_to_string("service.html", { "sv": rs, "username": xform.user.username, "id_string": xform.id_string}) restservice = service_tpl else: status = 'fail' message = _(u"Please fill in all required fields") if form.errors: for field in form: message += Template(u"{{ field.errors }}")\ .render(Context({'field': field})) if request.is_ajax(): response = {'status': status, 'message': message} if restservice: response["restservice"] = u"%s" % restservice return HttpResponse(json.dumps(response)) data['status'] = status data['message'] = message data['list_services'] = RestService.objects.filter(xform=xform) data['form'] = form data['username'] = username data['id_string'] = id_string return render(request, "add-service.html", data)