Python django.template.context 模块,Context() 实例源码

我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用django.template.context.Context()

项目:RobotFrameworkReporter    作者:ivanitskiy    | 项目源码 | 文件源码
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))
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
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
项目:vaultier    作者:Movile    | 项目源码 | 文件源码
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
项目:ims    作者:ims-team    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:django-open-lecture    作者:DmLitov4    | 项目源码 | 文件源码
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
项目:travlr    作者:gauravkulkarni96    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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
项目:CSCE482-WordcloudPlus    作者:ggaytan00    | 项目源码 | 文件源码
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
项目:producthunt    作者:davidgengler    | 项目源码 | 文件源码
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
项目:django-rtc    作者:scifiswapnil    | 项目源码 | 文件源码
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
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
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
项目:RobotFrameworkReporter    作者:ivanitskiy    | 项目源码 | 文件源码
def handler404(request, template_name='404.html'):
    t = get_template(template_name)
    ctx = Context({})
    return HttpResponseNotFound(t.render(ctx))
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:django-formtools-addons    作者:vikingco    | 项目源码 | 文件源码
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)
项目:habilitacion    作者:GabrielBD    | 项目源码 | 文件源码
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
项目:django-admin-footer    作者:collab-project    | 项目源码 | 文件源码
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)
项目:django-admin-appmenu    作者:collab-project    | 项目源码 | 文件源码
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)
项目:vaultier    作者:Movile    | 项目源码 | 文件源码
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)
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def __str__(self):
        tpl = get_template(self.template)
        return mark_safe(tpl.render(Context(self.get_context())))
项目:django-clubhouse    作者:chazmead    | 项目源码 | 文件源码
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))
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
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)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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)
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
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,
    }))
项目:mes    作者:osess    | 项目源码 | 文件源码
def __str__(self):
        tpl = get_template(self.template)
        return mark_safe(tpl.render(Context(self.get_context())))
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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)
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
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)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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)
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
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)