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

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

项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        key = self.cache_key(template_name, template_dirs)
        template_tuple = self.template_cache.get(key)
        # A cached previous failure:
        if template_tuple is TemplateDoesNotExist:
            raise TemplateDoesNotExist(template_name)
        elif template_tuple is None:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = Template(template, origin, template_name, self.engine)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    self.template_cache[key] = (template, origin)
            self.template_cache[key] = (template, None)
        return self.template_cache[key]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def test_send_email_message(self, get_template, send_mail):
        # send_email_message comes up with the expected template names
        # and calls send_mail with the expected arguments
        test_template = Template("test template")
        get_template.return_value = test_template

        context = {'a': 1, 'b': 2}
        send_email_message("TESTNAME", "from_address", [1, 2], [], context)

        args, kwargs = get_template.call_args_list[0]
        expected_template_name = "tutorials/email/TESTNAME/subject.txt"
        self.assertEqual(expected_template_name, args[0])

        args, kwargs = get_template.call_args_list[1]
        expected_template_name = "tutorials/email/TESTNAME/body.txt"
        self.assertEqual(expected_template_name, args[0])

        self.assertEqual(1, send_mail.call_count)
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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))
项目:django-echoices    作者:mbourqui    | 项目源码 | 文件源码
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)
项目:django-echoices    作者:mbourqui    | 项目源码 | 文件源码
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)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def test_preferences_cp(self):
        request = RequestFactory().get('/')
        context = context_processors.preferences_cp(request)

        # context should have preferences.
        my_preferences = context['preferences']

        # preferences should have test MyPreferences object member.
        my_preferences = my_preferences.MyPreferences
        self.failUnless(isinstance(my_preferences, MyPreferences),
                        "%s should be instance of MyPreferences." % my_preferences)

        # With preferences_cp is loaded as a TEMPLATE_CONTEXT_PROCESSORS
        # templates should have access to preferences object.
        context_instance = RequestContext(request)
        t = Template("{% if preferences %}{{ preferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "preferences should be \
available in template context.")

        t = Template("{% if preferences.MyPreferences %}{{ \
preferences.MyPreferences }}{% endif %}")
        self.failUnless(t.render(context_instance), "MyPreferences should be \
available as part of preferences var in template context.")
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
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))
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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))
项目:django-lb-workflow    作者:vicalloy    | 项目源码 | 文件源码
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)
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
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))
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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))
项目:django-echarts    作者:kinegratii    | 项目源码 | 文件源码
def echarts_js_dependencies(context, *args):
    dependencies = []

    def _add(_x):
        if _x not in dependencies:
            dependencies.append(_x)

    for a in args:
        if hasattr(a, 'js_dependencies'):
            for d in a.js_dependencies:
                _add(d)
        elif isinstance(a, six.text_type):
            _add(a)
    if len(dependencies) > 1:
        dependencies.remove('echarts')
        dependencies = ['echarts'] + list(dependencies)
    links = map(DJANGO_ECHARTS_SETTINGS.host_store.generate_js_link, dependencies)

    return template.Template(
        '<br/>'.join(['<script src="{link}"></script>'.format(link=l) for l in links])
    ).render(context)
项目:dd-trace-py    作者:DataDog    | 项目源码 | 文件源码
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
项目:django-mpathy    作者:craigds    | 项目源码 | 文件源码
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>'
    )
项目:service-notifications    作者:rehive    | 项目源码 | 文件源码
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
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
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
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
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))
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
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
项目:rudi    作者:lexxodus    | 项目源码 | 文件源码
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
项目:django-gateone    作者:jimmy201602    | 项目源码 | 文件源码
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))
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
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": forms.ModelForm,
            "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
        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))
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def get_initial(self, *args, **kwargs):
        event = Event.objects.get(pk=self.kwargs['pk'])

        event_data = dict(event.__dict__)

        if not event_data.get('creator_name', None):
            event_data['creator_name'] = " ".join([event.creator_cons.firstname, event.creator_cons.lastname])

        return {
                    'event': event,
                    'volunteer_count': 4000 if event.capacity == 0 else event.capacity * 40,
                    'subject': "Please come to my %s event" % event.event_type.name,
                    'message': Template("""Hello --

I'm hoping to get more attendees at my event, {{ event.name }}! Can you make it? We're almost across the finish line and we need to keep up the momentum.


Thanks!


{{ event.creator_cons.firstname }}""").render(Context({'event': event}))
                }
项目:studentsdb    作者:PyDev777    | 项目源码 | 文件源码
def test_pagenav_tag(self):
        """Pagenav tag returns page navigation widget"""
        # prepare paginator
        paginator = Paginator([1, 2, 3, 4], 1)
        my_list = paginator.page('1')
        test_url = 'test/'

        # render template with pagenav tag
        out = Template(
            "{% load pagenav %}"
            "{% pagenav object_list base_url order_by reverse cur_month is_paginated paginator %}"
        ).render(Context({
            'object_list': my_list, 'base_url': test_url, 'order_by': None, 'reverse': None, 'cur_month': None, 'is_paginated': True, 'paginator': paginator
        }))

        # paginator should create 4 pages
        self.assertIn('<nav>', out)
        self.assertIn('<a href="test/?page=1" class="content-link">1</a>', out)
        self.assertIn('<a href="test/?page=2" class="content-link">2</a>', out)
        self.assertIn('<a href="test/?page=3" class="content-link">3</a>', out)
        self.assertIn('<a href="test/?page=4" class="content-link">4</a>', out)
项目:studentsdb    作者:PyDev777    | 项目源码 | 文件源码
def test_str2int(self):
        """Test str2int template filter"""
        out = Template(
            "{% load str2int %}"
            "{% if 36 == '36'|str2int %}"
            "it works"
            "{% endif %}"
        ).render(Context({}))

        # check for our addition operation result
        self.assertIn("it works", out)

        out = Template(
            "{% load str2int %}"
            "{% if 0 == 'Zero'|str2int %}"
            "it works"
            "{% endif %}"
        ).render(Context({}))

        # check for our addition operation result
        self.assertIn("it works", out)
项目:django-chartwerk    作者:DallasMorningNews    | 项目源码 | 文件源码
def get_embed_code(self, size='double'):
        """Return the embed code for the chart."""
        def simple_string(split_string):
            """Return a string stripped of extra whitespace."""
            return ' '.join(split_string.split())

        template_object = template.Template(app_settings.EMBED_TEMPLATE)
        template_context_object = app_settings.EMBED_TEMPLATE_CONTEXT(self)
        template_context_object.update({
            'size': size,
            'id': self.slug,
            'dimensions': json.dumps(self.embed_data).replace('"', '&quot;'),
        })
        return simple_string(
            template_object.render(template.Context(
                template_context_object
            ))
        )
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        key = self.cache_key(template_name, template_dirs)
        template_tuple = self.template_cache.get(key)
        # A cached previous failure:
        if template_tuple is TemplateDoesNotExist:
            raise TemplateDoesNotExist(template_name)
        elif template_tuple is None:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = Template(template, origin, template_name, self.engine)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning the source and display name for the template
                    # we were asked to load. This allows for correct identification (later)
                    # of the actual template that does not exist.
                    self.template_cache[key] = (template, origin)
            self.template_cache[key] = (template, None)
        return self.template_cache[key]
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
项目:eduDjango    作者:yuzhou6    | 项目源码 | 文件源码
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
项目:eduDjango    作者:yuzhou6    | 项目源码 | 文件源码
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))
项目:django_wagtail_boilerplate    作者:AccentDesign    | 项目源码 | 文件源码
def test_rendered(self):
        page = Page.objects.get(pk=4)
        context = Context({
            'request': {},
            'page': page
        })
        template_to_render = Template(
            '{% load general_tags wagtailcore_tags %}'
            '{% breadcrumb %}'
        )
        rendered_template = template_to_render.render(context)
        self.assertInHTML(
            """
            <ol class="breadcrumb">
                <li><a href="/">Home</a></li>
                <li>Sub 1</li>
            </ol>
            """, rendered_template)
项目:django_wagtail_boilerplate    作者:AccentDesign    | 项目源码 | 文件源码
def test_page_passed_in_rendered(self):
        page = Page.objects.get(pk=4)
        context = Context({
            'request': {},
            'page': page
        })
        template_to_render = Template(
            '{% load general_tags wagtailcore_tags %}'
            '{% breadcrumb page %}'
        )
        rendered_template = template_to_render.render(context)
        self.assertInHTML(
            """
            <ol class="breadcrumb">
                <li><a href="/">Home</a></li>
                <li>Sub 1</li>
            </ol>
            """, rendered_template)
项目:django_wagtail_boilerplate    作者:AccentDesign    | 项目源码 | 文件源码
def test_showlinks_false_renders_no_links(self):
        page = Page.objects.get(pk=4)
        context = Context({
            'request': {},
            'page': page
        })
        template_to_render = Template(
            '{% load general_tags wagtailcore_tags %}'
            '{% breadcrumb page False %}'
        )
        rendered_template = template_to_render.render(context)
        self.assertInHTML(
            """
            <ol class="breadcrumb">
                <li>Home</li>
                <li>Sub 1</li>
            </ol>
            """, rendered_template)
项目:Django-IMOOC-Shop    作者:LBruse    | 项目源码 | 文件源码
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
项目:Django-IMOOC-Shop    作者:LBruse    | 项目源码 | 文件源码
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))
项目:fluentcms-jumbotron    作者:django-fluent    | 项目源码 | 文件源码
def test_default_jumbotron(self):
        """
        Default jumbotron rendering
        """
        page1 = self.create_page(slug='page1', title="Hello", content="<p>test</p>", button1_url='http://example.org/', button1_title="GO")

        template = Template('{% load fluent_contents_tags %}{% page_placeholder "content" %}')
        request = RequestFactory().get("/", HTTP_HOST='example.org')

        html = template.render(Context({'page': page1, 'request': request}))
        expected = '''<div class="jumbotron">
  <div class="container">
    <h1>Hello</h1>
    <p>test</p>
    <p><a class="btn btn-primary btn-lg" href="http://example.org/" role="button">GO</a></p>
  </div>
</div>'''
        self.assertEqual(slugify(strip_tags(html)), 'hello-test-go')
        self.assertHTMLEqual(html.strip(), expected)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def render_plugin(context, instance, placeholder, template, processors=None, current_app=None):
    """
    Renders a single plugin and applies the post processors to it's rendered
    content.
    """
    if current_app:
        context['request'].current_app = current_app
    if not processors:
        processors = []
    if isinstance(template, six.string_types):
        content = render_to_string(template, flatten_context(context))
    elif (isinstance(template, Template) or (hasattr(template, 'template') and
          hasattr(template, 'render') and isinstance(template.template, Template))):
        content = template.render(context)
    else:
        content = ''
    for processor in iterload_objects(get_cms_setting('PLUGIN_PROCESSORS')):
        content = processor(instance, placeholder, content, context)
    for processor in processors:
        content = processor(instance, placeholder, content, context)
    for processor in DEFAULT_PLUGIN_PROCESSORS:
        content = processor(instance, placeholder, content, context)
    return content
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_extenders_on_root(self):
        self._update_page(1, navigation_extenders="TestMenu")
        menu_pool.clear(settings.SITE_ID)
        context = self.get_context()

        tpl = Template("{% load menu_tags %}{% show_menu 0 100 100 100 %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(len(nodes[0].children), 4)
        self.assertEqual(len(nodes[0].children[3].children), 1)
        self._update_page(1, in_navigation=False)
        menu_pool.clear(settings.SITE_ID)
        tpl = Template("{% load menu_tags %}{% show_menu %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 5)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_language_chooser(self):
        # test simple language chooser with default args
        create_page("home", template="col_two.html", language="en-us", published=True)
        context = self.get_context(path="/")
        del context['request'].LANGUAGE_CODE
        tpl = Template("{% load menu_tags %}{% language_chooser %}")
        tpl.render(context)
        self.assertEqual(len(context['languages']), 1)
        # try a different template and some different args
        tpl = Template("{% load menu_tags %}{% language_chooser 'menu/test_language_chooser.html' %}")
        tpl.render(context)
        self.assertEqual(context['template'], 'menu/test_language_chooser.html')
        tpl = Template("{% load menu_tags %}{% language_chooser 'short' 'menu/test_language_chooser.html' %}")
        tpl.render(context)
        self.assertEqual(context['template'], 'menu/test_language_chooser.html')
        for lang in context['languages']:
            self.assertEqual(*lang)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_processors(self):
        """
        Tests that default plugin context processors are working, that plugin processors and plugin context processors
        can be defined in settings and are working and that extra plugin context processors can be passed to PluginContext.
        """
        def test_passed_plugin_context_processor(instance, placeholder, context):
            return {'test_passed_plugin_context_processor': 'test_passed_plugin_context_processor_ok'}

        t = u'{% load cms_tags %}' + \
            u'{{ plugin.counter }}|{{ plugin.instance.body }}|{{ test_passed_plugin_context_processor }}|{{ test_plugin_context_processor }}'
        instance, plugin = CMSPlugin.objects.all()[0].get_plugin_instance()
        instance.render_template = Template(t)
        context = PluginContext({'original_context_var': 'original_context_var_ok'}, instance,
                                self.test_placeholders['main'], processors=(test_passed_plugin_context_processor,))
        plugin_rendering._standard_processors = {}
        c = render_plugins((instance,), context, self.test_placeholders['main'])
        r = "".join(c)
        self.assertEqual(r, u'1|' + self.test_data[
            'text_main'] + '|test_passed_plugin_context_processor_ok|test_plugin_context_processor_ok|' +
                            self.test_data['text_main'] + '|main|original_context_var_ok|test_plugin_processor_ok|' + self.test_data[
                                'text_main'] + '|main|original_context_var_ok')
        plugin_rendering._standard_processors = {}
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_submenu_nephews(self):
        context = self.get_context(path=self.get_page(2).get_absolute_url())
        tpl = Template("{% load menu_tags %}{% show_sub_menu 100 1 1 %}")
        tpl.render(context)
        nodes = context["children"]
        # P2 is the selected node
        self.assertTrue(nodes[0].selected)
        # Should include P10 but not P11
        self.assertEqual(len(nodes[1].children), 1)
        self.assertFalse(nodes[1].children[0].children)

        tpl = Template("{% load menu_tags %}{% show_sub_menu 100 1 %}")
        tpl.render(context)
        nodes = context["children"]
        # should now include both P10 and P11
        self.assertEqual(len(nodes[1].children), 1)
        self.assertEqual(len(nodes[1].children[0].children), 1)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_menu(self):
        context = self.get_context()
        # test standard show_menu
        tpl = Template("{% load menu_tags %}{% show_menu %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].selected, True)
        self.assertEqual(nodes[0].sibling, False)
        self.assertEqual(nodes[0].descendant, False)
        self.assertEqual(nodes[0].children[0].descendant, True)
        self.assertEqual(nodes[0].children[0].children[0].descendant, True)
        self.assertEqual(nodes[0].get_absolute_url(), self.get_pages_root())
        self.assertEqual(nodes[1].get_absolute_url(), self.get_page(4).get_absolute_url())
        self.assertEqual(nodes[1].sibling, True)
        self.assertEqual(nodes[1].selected, False)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_menu_num_queries(self):
        context = self.get_context()
        # test standard show_menu
        with self.assertNumQueries(7):
            """
            The queries should be:
                get all pages
                get all page permissions
                get all titles
                get the menu cache key
                create a savepoint
                set the menu cache key
                release the savepoint
            """
            tpl = Template("{% load menu_tags %}{% show_menu %}")
            tpl.render(context)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_language_chooser(self):
        # test simple language chooser with default args
        lang_settings = copy.deepcopy(get_cms_setting('LANGUAGES'))
        lang_settings[1][0]['public'] = False
        with self.settings(CMS_LANGUAGES=lang_settings):
            context = self.get_context(path=self.get_page(3).get_absolute_url())
            tpl = Template("{% load menu_tags %}{% language_chooser %}")
            tpl.render(context)
            self.assertEqual(len(context['languages']), 3)
            # try a different template and some different args
            tpl = Template("{% load menu_tags %}{% language_chooser 'menu/test_language_chooser.html' %}")
            tpl.render(context)
            self.assertEqual(context['template'], 'menu/test_language_chooser.html')
            tpl = Template("{% load menu_tags %}{% language_chooser 'short' 'menu/test_language_chooser.html' %}")
            tpl.render(context)
            self.assertEqual(context['template'], 'menu/test_language_chooser.html')
            for lang in context['languages']:
                self.assertEqual(*lang)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_menu_below_id(self):
        page2 = self.get_page(2)
        page2.reverse_id = "hello"
        page2.save()
        page2 = self.reload(page2)
        self.assertEqual(page2.reverse_id, "hello")
        page5 = self.get_page(5)
        context = self.get_context(path=page5.get_absolute_url())
        tpl = Template("{% load menu_tags %}{% show_menu_below_id 'hello' %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 1)
        page3_url = self.get_page(3).get_absolute_url()
        self.assertEqual(nodes[0].get_absolute_url(), page3_url)
        page2.in_navigation = False
        page2.save()
        context = self.get_context(path=page5.get_absolute_url())
        tpl = Template("{% load menu_tags %}{% show_menu_below_id 'hello' %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), page3_url)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_home_not_in_menu(self):
        page1 = self.get_page(1)
        page1.in_navigation = False
        page1.save()
        page4 = self.get_page(4)
        page4.in_navigation = False
        page4.save()
        context = self.get_context()
        tpl = Template("{% load menu_tags %}{% show_menu 0 100 100 100 %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 1)
        self.assertEqual(nodes[0].get_absolute_url(), self.get_page(2).get_absolute_url())
        self.assertEqual(nodes[0].children[0].get_absolute_url(), self.get_page(3).get_absolute_url())
        page4 = self.get_page(4)
        page4.in_navigation = True
        page4.save()
        menu_pool.clear(settings.SITE_ID)
        context = self.get_context()
        tpl = Template("{% load menu_tags %}{% show_menu 0 100 100 100 %}")
        tpl.render(context)
        nodes = context['children']
        self.assertEqual(len(nodes), 2)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_breadcrumb_invisible(self):
        # Must use the drafts to find the parent when calling create_page
        parent = Page.objects.drafts().get(title_set__title='P3')
        invisible_page = create_page("invisible", "nav_playground.html", "en",
            parent=parent, published=True, in_navigation=False)
        context = self.get_context(path=invisible_page.get_absolute_url())
        tpl = Template("{% load menu_tags %}{% show_breadcrumb %}")
        tpl.render(context)
        nodes = context['ancestors']
        self.assertEqual(len(nodes), 3)
        tpl = Template("{% load menu_tags %}{% show_breadcrumb 0 'menu/breadcrumb.html' 1 %}")
        tpl.render(context)
        nodes = context['ancestors']
        self.assertEqual(len(nodes), 3)
        tpl = Template("{% load menu_tags %}{% show_breadcrumb 0 'menu/breadcrumb.html' 0 %}")
        tpl.render(context)
        nodes = context['ancestors']
        self.assertEqual(len(nodes), 4)
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def test_show_submenu_num_queries(self):
        page = self.get_page(6)
        subpage = self.get_page(8)
        context = self.get_context(page.get_absolute_url())

        # test standard show_menu
        with self.assertNumQueries(7):
            """
            The queries should be:
                get all pages
                get all page permissions
                get all titles
                get the menu cache key
                create a savepoint
                set the menu cache key
                release the savepoint
            """
            tpl = Template("{% load menu_tags %}{% show_sub_menu %}")
            tpl.render(context)
            nodes = context['children']
            self.assertEqual(len(nodes), 1)
            self.assertEqual(nodes[0].id, subpage.pk)