示例#1
0
    def test_template_pack_override(self):
        current_pack = self.current_template_pack
        override_pack = current_pack == 'uni_form' and 'bootstrap' or 'uni_form'

        # Syntax {% crispy form 'template_pack_name' %}
        template = loader.get_template_from_string(u"""
            {%% load crispy_forms_tags %%}
            {%% crispy form "%s" %%}
        """ % override_pack)
        c = Context({'form': TestForm()})
        html = template.render(c)

        # Syntax {% crispy form helper 'template_pack_name' %}
        template = loader.get_template_from_string(u"""
            {%% load crispy_forms_tags %%}
            {%% crispy form form_helper "%s" %%}
        """ % override_pack)
        c = Context({'form': TestForm(), 'form_helper': FormHelper()})
        html2 = template.render(c)

        if (current_pack == 'uni_form'):
            self.assertTrue('control-group' in html)
            self.assertTrue('control-group' in html2)
        else:
            self.assertTrue('uniForm' in html)
            self.assertTrue('uniForm' in html2)
示例#2
0
 def render(self, context):
     block = get_or_create_block(self.address)
     context[self.var_name] = {
         'title': get_template_from_string(block.title).render(context),
         'content': get_template_from_string(block.content).render(context),
     }
     return ""
示例#3
0
    def test_template_pack_override(self):
        current_pack = settings.CRISPY_TEMPLATE_PACK
        override_pack = current_pack == "uni_form" and "bootstrap" or "uni_form"

        # Syntax {% crispy form 'template_pack_name' %}
        template = get_template_from_string(
            u"""
            {%% load crispy_forms_tags %%}
            {%% crispy form "%s" %%}
        """
            % override_pack
        )
        c = Context({"form": TestForm()})
        html = template.render(c)

        # Syntax {% crispy form helper 'template_pack_name' %}
        template = get_template_from_string(
            u"""
            {%% load crispy_forms_tags %%}
            {%% crispy form form_helper "%s" %%}
        """
            % override_pack
        )
        c = Context({"form": TestForm(), "form_helper": FormHelper()})
        html2 = template.render(c)

        if current_pack == "uni_form":
            self.assertTrue("control-group" in html)
            self.assertTrue("control-group" in html2)
        else:
            self.assertTrue("uniForm" in html)
            self.assertTrue("uniForm" in html2)
示例#4
0
    def load_template(self, template_name, template_dirs=None):
        key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])

        
        if settings.DEBUG or key not in self.template_cache:

            if os.path.splitext(template_name)[1] in ('.jade',):
                source, display_name = self.load_template_source(template_name, template_dirs)
                source=process(source,filename=template_name,compiler=Compiler)
                origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
                template = get_template_from_string(source, origin, template_name)
            else:
                template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
                except TemplateDoesNotExist:
                    # If compiling the template we found raises TemplateDoesNotExist,
                    # back off to returning he 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.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
示例#5
0
    def send(cls, *args, **kwargs):

        n = Notification()
        template = kwargs.get('template')
        language = kwargs.get('language', 'en')
        ctx = kwargs.get('ctx')
        recipients = kwargs.get('recipients')
        sent_from = kwargs.get('sent_from', settings.DEFAULT_FROM)

        n.send_by_mailer = kwargs.get('send_by_mailer', True)
        n.send_on_save = kwargs.get('send_on_save')

        if language == 'en-us':
            language = 'en'

        current_domain = Site.objects.get_current().domain
        ctx['site_url'] = '%s://%s' % ('http', current_domain)
        ctx['STATIC_URL'] = settings.STATIC_URL

        try:
            template = NotificationTemplateContent.objects.get(template__name=template, lang=language)

            n.subject = get_template_from_string(template.subject).render(Context(ctx))
            n.body = get_template_from_string(template.body).render(Context(ctx))
            n.html_body = get_template_from_string(template.html_body).render(Context(ctx))
            n.recipients = ','.join(recipients)
            n.sent_from = sent_from

        except NotificationTemplateContent.DoesNotExist:
            pass

        except Exception, e:
            print e
示例#6
0
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)

    ImplementationFactory.instance.get_singleton_of('MailerServiceBase').send_email(
        ticket,
        ticket.defendant.details.email,
        subject,
        body,
        'MassContact',
    )
示例#7
0
def send_new_answer_payload(sender, instance, created, **kwargs):
    answer = instance
    if created:
        new_answer_template = answer.message.writeitinstance.\
                                new_answer_notification_template
        htmly = get_template_from_string(new_answer_template.template_html)
        texty = get_template_from_string(new_answer_template.template_text)
        if settings.SEND_ALL_EMAILS_FROM_DEFAULT_FROM_EMAIL:
            from_email = settings.DEFAULT_FROM_EMAIL
        else:
            from_email = answer.message.writeitinstance.slug+"@"+\
                            settings.DEFAULT_FROM_DOMAIN
        subject_template = new_answer_template.subject_template
        for subscriber in answer.message.subscribers.all():
            d = Context({
                'user': answer.message.author_name,
                'person':answer.person,
                'message':answer.message,
                'answer':answer
            })
            html_content = htmly.render(d)
            txt_content = texty.render(d)
            subject = subject_template % {
            'person':answer.person.name,
            'message':answer.message.subject
            }
            msg = EmailMultiAlternatives(subject, \
                        txt_content, from_email, [subscriber.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        if answer.message.writeitinstance.notify_owner_when_new_answer:
            d = Context({
                'user': answer.message.writeitinstance.owner,
                'person':answer.person,
                'message':answer.message,
                'answer':answer
            })
            html_content = htmly.render(d)
            txt_content = texty.render(d)
            subject = subject_template % {
            'person':answer.message.writeitinstance.owner.username,
            'message':answer.message.subject
            }
            msg = EmailMultiAlternatives(subject, txt_content,\
                         from_email, \
                         [answer.message.writeitinstance.owner.email])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        for webhook in answer.message.writeitinstance.answer_webhooks.all():
            payload = {
                    'message_id':'/api/v1/message/{0}/'.\
                                    format(answer.message.id),
                    'content': answer.content,
                    'person':answer.person.name,
                    'person_id':answer.person.popit_url
            }
            requests.post(webhook.url, data=payload)
 def test_template_pack_override_wrong(self):
     try:
         loader.get_template_from_string(u"""
             {% load crispy_forms_tags %}
             {% crispy form 'foo' %}
         """)
     except TemplateSyntaxError:
         pass
示例#9
0
 def test_ifblock_renders_child_with_wrapper_when_child_block_exists(self):
     expected = """<p>base1a</p><p>expected1</p><p>base1b</p>"""
     
     t1 = get_template_from_string(base1)
     t2 = get_template_from_string(exp1)
     
     result = t2.render(Context({'baseA': t1}))
     
     self.assertEqual(result, expected, result)
示例#10
0
 def test_ifblock_renders_child_with_wrapper_when_child_block_exists_and_ignores_super(self):
     expected = """<p>base1a</p><p>alternate1</p><p>base1b</p>"""
     
     t1 = get_template_from_string(base1)
     t2 = get_template_from_string(alt1)
     
     result = t2.render(Context({'baseC': t1}))
     
     self.assertEqual(result, expected, result)
示例#11
0
 def test_ifblock_renders_both_children_with_wrapper_when_super_used(self):
     expected = """<p>base1a</p><p>expected1</p><p>alternate1</p><p>base1b</p>"""
     
     t1 = get_template_from_string(base1)
     t2 = get_template_from_string(exp1)
     t3 = get_template_from_string(alt1)
     
     result = t3.render(Context({'baseC': t2, 'baseA': t1}))
     
     self.assertEqual(result, expected, result)
示例#12
0
 def test_ifblock_renders_child_with_double_wrapper(self):
     expected = """<p>base1a</p><p>base2a</p><p>expected1</p><p>base2b</p><p>base1b</p>"""
     
     t1 = get_template_from_string(base1)
     t2 = get_template_from_string(base2)
     t3 = get_template_from_string(exp1)
     
     result = t3.render(Context({'baseA': t2, 'baseX': t1}))
     
     self.assertEqual(result, expected, result)
示例#13
0
 def setUp(self):
     super(NewAnswerNotificationToSubscribers, self).setUp()
     self.instance = WriteItInstance.objects.all()[0]
     self.message = Message.objects.all()[0]
     self.subscriber = Subscriber.objects.create(message=self.message, email=self.message.author_email)
     self.pedro = Person.objects.all()[0]
     self.owner = User.objects.all()[0]
     self.instance.new_answer_notification_template.subject_template = 'weeena pelao %(person)s %(message)s'
     self.instance.new_answer_notification_template.save()
     self.template_str_html = get_template_from_string(self.instance.new_answer_notification_template.template_html)
     self.template_str_txt = get_template_from_string(self.instance.new_answer_notification_template.template_text)
示例#14
0
 def get_template(self, template_model=None):
     if isinstance(template_model, str):
         return get_template(template_model)
     if template_model:
         try:
             return get_template_from_string(template_model.content)
         except TemplateSyntaxError, e:
             if settings.TEMPLATE_DEBUG:
                 return get_template_from_string(
                         _('Cannot render page template "%(name)".\
                            Please correct template errors: %(errors)'
                            % {'name':template_model.name, 'errors': e}))
示例#15
0
    def test_json_placeholder(self):
        tpl = "{% load pages_tags %}{% jsonplaceholder p1 as v %}{{ v.a }}"

        template = get_template_from_string(tpl)
        page = self.new_page({"p1": '{"a":1}'})
        context = Context({"current_page": page})
        self.assertEqual(template.render(context), "1")

        tpl = "{% load pages_tags %}{% jsonplaceholder p1 %}"
        template = get_template_from_string(tpl)
        page = self.new_page({"p1": "wrong"})
        context = Context({"current_page": page})
        self.assertEqual(template.render(context), "wrong")
示例#16
0
 def test_json_placeholder(self):
     tpl = ("{% load pages_tags %}{% jsonplaceholder p1 as v %}{{ v.a }}")
     
     template = get_template_from_string(tpl)
     page = self.new_page({'p1': '{"a":1}'})
     context = Context({'current_page': page})
     self.assertEqual(template.render(context), u'1')
     
     tpl = ("{% load pages_tags %}{% jsonplaceholder p1 %}")
     template = get_template_from_string(tpl)
     page = self.new_page({'p1': 'wrong'})
     context = Context({'current_page': page})
     self.assertEqual(template.render(context), u'wrong')
示例#17
0
def index(request, path=None):
    f = open("/tmp/log.txt", "a")
    f.write("path: %s\n" % str(path))
    f.write("request: %s\n" % str(request))
    path = request.GET.get('page', None)
    if path == '':
        path = 'index'
    f.write("pth: %s \n" % (path))
    if path is None:
        # workaround in history tokens: must have a query
        return HttpResponseRedirect("./?page=#index")
    p = Page.objects.get(name=path)
    f.write("page: %s \n" % (str(p)))
    f.close()
    args = {'title': p.name,
            'noscript': p.text
            }
    context_instance=RequestContext(request)
    context_instance.autoescape=False
    try:
        template = Page.objects.get(name='index.html')
    except Page.DoesNotExist:
        template = None
    if not template:
        return render_to_response('index.html', args, context_instance)
    tpl = loader.get_template_from_string(template)
    context_instance.update(args)
    tpl = tpl.render(context_instance)
    return HttpResponse(tpl)
示例#18
0
    def test_choice_multichoice_question_form(self):
        choice_question = ChoiceQuestion.objects.create(
            text="Multichoice question",
            multichoice=True
        )

        choice_question.choices = [
            Choice.objects.create(label='42 what was the question?'),
            Choice.objects.create(label='43'),
        ]

        form = ChoiceQuestionForm(
            question=choice_question,
            content_object=self.member,
        )

        template = get_template_from_string(u"""
                {% load crispy_forms_tags %}
                {% crispy form %}
        """)
        nt.eq_(form.is_valid(), False)
        c = Context({'form': form})
        html = template.render(c)

        nt.assert_true('42 what was the question' in html)

        # test that inline checkboxes are rendering instead of radio buttons
        nt.assert_true('checkbox inline' in html)
示例#19
0
 def load_template(self, template_name, template_dirs=None):
     if template_name not in self.template_cache:
         template, origin = self.find_template(template_name, template_dirs)
         if not hasattr(template, "render"):
             template = get_template_from_string(template, origin, template_name)
         self.template_cache[template_name] = template
     return self.template_cache[template_name], None
    def test_inputs(self):
        form_helper = FormHelper()
        form_helper.add_input(Submit('my-submit', 'Submit', css_class="button white"))
        form_helper.add_input(Reset('my-reset', 'Reset'))
        form_helper.add_input(Hidden('my-hidden', 'Hidden'))
        form_helper.add_input(Button('my-button', 'Button'))

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('button white' in html)
        self.assertTrue('id="submit-id-my-submit"' in html)
        self.assertTrue('id="reset-id-my-reset"' in html)
        self.assertTrue('name="my-hidden"' in html)
        self.assertTrue('id="button-id-my-button"' in html)

        if self.current_template_pack == 'uni_form':
            self.assertTrue('submit submitButton' in html)
            self.assertTrue('reset resetButton' in html)
            self.assertTrue('class="button"' in html)
        else:
            self.assertTrue('class="btn"' in html)
            self.assertTrue('btn btn-primary' in html)
            self.assertTrue('btn btn-inverse' in html)
            self.assertEqual(len(re.findall(r'<input[^>]+> <', html)), 8)
    def load_template(self, template_name, template_dirs=None):
        if connection.tenant:
            key = '-'.join([str(connection.tenant.pk), template_name])
        else:
            key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to
            # differentiate
            if connection.tenant:
                key = '-'.join([str(connection.tenant.pk), template_name,
                                hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])
            else:
                key = '-'.join([template_name, hashlib.sha1(force_bytes('|'.join(template_dirs))).hexdigest()])

        if key not in self.template_cache:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(template, origin, template_name)
                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.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
示例#22
0
文件: tests.py 项目: Bauke900/dnevnik
    def test_uni_form_formset(self):
        template = get_template_from_string(
            u"""
            {% load uni_form_tags %}
            {% uni_form testFormSet formset_helper %}
        """
        )

        form_helper = FormHelper()
        form_helper.form_id = "thisFormsetRocks"
        form_helper.form_class = "formsets-that-rock"
        form_helper.form_method = "POST"
        form_helper.form_action = "simpleAction"

        TestFormSet = formset_factory(TestForm, extra=3)
        testFormSet = TestFormSet()

        c = Context({"testFormSet": testFormSet, "formset_helper": form_helper, "csrf_token": _get_new_csrf_key()})
        html = template.render(c)

        self.assertEqual(html.count("<form"), 1)
        self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1)

        self.assertTrue('class="uniForm formsets-that-rock"' in html)
        self.assertTrue('method="post"' in html)
        self.assertTrue('id="thisFormsetRocks">' in html)
        self.assertTrue('action="%s"' % reverse("simpleAction") in html)
示例#23
0
文件: tests.py 项目: Bauke900/dnevnik
    def test_uni_form_helper_inputs(self):
        form_helper = FormHelper()
        submit = Submit("my-submit", "Submit", css_class="button white")
        reset = Reset("my-reset", "Reset")
        hidden = Hidden("my-hidden", "Hidden")
        button = Button("my-button", "Button")
        form_helper.add_input(submit)
        form_helper.add_input(reset)
        form_helper.add_input(hidden)
        form_helper.add_input(button)

        template = get_template_from_string(
            u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """
        )
        c = Context({"form": TestForm(), "form_helper": form_helper})
        html = template.render(c)

        # NOTE: Not sure why this is commented
        self.assertTrue('class="submit submitButton button white"' in html)
        self.assertTrue('id="submit-id-my-submit"' in html)

        self.assertTrue('class="reset resetButton"' in html)
        self.assertTrue('id="reset-id-my-reset"' in html)

        self.assertTrue('name="my-hidden"' in html)

        self.assertTrue('class="button"' in html)
        self.assertTrue('id="button-id-my-button"' in html)
示例#24
0
    def render(self, style='compact', template_name="tri_form/form.html"):
        """
        :type style: str| unicode
        :type template_name: str | unicode | None
        """
        self.style = style
        r = []
        for field in self.fields:
            context = {
                'form': self,
                'field': field,
            }
            if field.template_string is not None:
                r.append(get_template_from_string(field.template_string, origin='tri.form', name='Form.render').render(Context(context)))
            else:
                r.append(render_to_string(field.template.format(style=style), context))
        if self.is_full_form:
            r.append(AVOID_EMPTY_FORM)

        if template_name is None:
            return mark_safe('\n'.join(r))
        else:
            return render_to_string(
                context_instance=RequestContext(self.request, dict(form=self)),
                template_name=template_name,
            )
示例#25
0
    def clean_template(self):
        # Get the settings module. If the site isn't set, we don't raise an
        # error since the site field will.
        try:
            site_id = int(self.cleaned_data.get('site', None))
        except (ValueError, TypeError):
            return
        settings_module = self.settings_modules.get(site_id, None)
        if settings_module is None:
            return

        # So that inheritance works in the site's context, register a new
        # function for "extends" that uses the site's TEMPLATE_DIRS instead.
        def new_do_extends(parser, token):
            node = loader.do_extends(parser, token)
            node.template_dirs = settings_module.TEMPLATE_DIRS
            return node

        register = template.Library()
        register.tag('extends', new_do_extends)
        template.builtins.append(register)

        # Now validate the template using the new TEMPLATE_DIRS, making sure to
        # reset the extends function in any case.
        error = None
        template_string = self.cleaned_data['template']
        try:
            tmpl = loader.get_template_from_string(template_string)
            tmpl.render(template.Context({}))
        except template.TemplateSyntaxError, e:
            error = e
示例#26
0
    def render(self, context):
        try:
            try:
                sort = context['request'].GET['sort']
            except KeyError:
                #fall back on this
                sort = context.get('sort', '')
            sort_key = self.sort_key.resolve(context)
            text = self.text.resolve(context)

            # add arrows
            try:
                sort_base = sort_key.lstrip('-')
                if sort[0] == '-' and sort[1:] == sort_base:
                    text = text + '&#x25BC;'
                    sort_key = sort_base
                elif sort_base == sort:
                    text = text + '&#x25B2;'
                    sort_key = '-' + sort_base
            except IndexError:
                pass

            context.push()
            context['key'] = sort_key
            context['text'] = mark_safe(text)
            output = get_template_from_string(self.__TMPL__).render(context)
            context.pop()
            return output
        except:
            if settings.DEBUG:
                raise
            raise
            return ''
示例#27
0
    def test_ga_site_tracking(self):
        """
        """
        shop = Shop.objects.get(pk=1)
        shop.google_analytics_id = ""
        shop.ga_site_tracking = False
        shop.ga_ecommerce_tracking = False
        shop.save()

        template = get_template_from_string(
            """{% load lfs_tags %}{% google_analytics_tracking %}""")

        content = template.render(Context())
        self.failIf(content.find("pageTracker") != -1)

        # Enter a google_analytics_id
        shop.google_analytics_id = "UA-XXXXXXXXXX"
        shop.save()

        # But this is not enough
        content = template.render(Context())
        self.failIf(content.find("pageTracker") != -1)

        # It has to be activated first
        shop.ga_site_tracking = True
        shop.save()

        # Now it works and "pageTracker" is found
        content = template.render(Context())
        self.failIf(content.find("pageTracker") == -1)
示例#28
0
 def render_form(self, form):
     template = get_template_from_string("""
         {% load crispy_forms_tags %}
         {% crispy form %}
     """)
     c = Context({'form': form})
     return template.render(c)
示例#29
0
文件: tests.py 项目: Bauke900/dnevnik
    def test_change_layout_dynamically_delete_field(self):
        template = get_template_from_string(
            u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """
        )

        form = TestForm()
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Fieldset(u"Company Data", "is_company", "email", "password1", "password2", css_id="multifield_info"),
                Column("first_name", "last_name", css_id="column_name"),
            )
        )

        # We remove email field on the go
        # Layout needs to be adapted for the new form fields
        del form.fields["email"]
        del form_helper.layout.fields[0].fields[1]

        c = Context({"form": form, "form_helper": form_helper})
        html = template.render(c)
        self.assertFalse("email" in html)
示例#30
0
文件: tests.py 项目: Bauke900/dnevnik
    def test_second_layout_multifield_column_buttonholder_submit(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                MultiField(
                    "Some company data", "is_company", "email", "password1", "password2", css_id="multifield_info"
                ),
                Column("first_name", "last_name", css_id="column_name"),
                ButtonHolder(Submit("Save", "Save", css_class="button white")),
            )
        )

        template = get_template_from_string(
            u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """
        )
        c = Context({"form": TestForm(), "form_helper": form_helper})
        html = template.render(c)

        self.assertTrue("multiField" in html)
        self.assertTrue("formColumn" in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('div class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="save"' in html)
示例#31
0
    def load_template(self, template_name, template_dirs=None):
        if not template_name.endswith('.shpaml'):
            raise TemplateDoesNotExist(template_name)

        template, origin = self.find_template(template_name, template_dirs)
        if not hasattr(template, 'render'):
            try:
                template = get_template_from_string(template, origin,
                                                    template_name)
            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.
                return template, origin

        return template, None
示例#32
0
 def get_parent(self, context):
     if self.parent_name_expr:
         self.parent_name = self.parent_name_expr.resolve(context)
     parent = self.parent_name
     if not parent:
         error_msg = "Invalid template name in 'extends' tag: %r." % parent
         if self.parent_name_expr:
             error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token
         raise TemplateSyntaxError, error_msg
     if hasattr(parent, 'render'):
         return parent  # parent is a Template object
     try:
         source, origin = find_template_source(parent, self.template_dirs)
     except TemplateDoesNotExist:
         raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
     else:
         return get_template_from_string(source, origin, parent)
示例#33
0
    def test_i18n(self):
        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form.helper %}
        """)
        form = TestForm()
        form_helper = FormHelper()
        form_helper.layout = Layout(
            HTML(_("i18n text")),
            Fieldset(
                _("i18n legend"),
                'first_name',
                'last_name',
            ))
        form.helper = form_helper

        html = template.render(Context({'form': form}))
    def test_inlinecompile_tag(self):
        with patch(
                "static_precompiler.templatetags.compile_static.get_compiler_by_name"
        ) as mocked_get_compiler_by_name:
            mocked_compiler = MagicMock()
            mocked_compiler.compile_source.return_value = "compiled"
            mocked_get_compiler_by_name.return_value = mocked_compiler
            template = get_template_from_string(
                """{% load compile_static %}{% inlinecompile compiler='sass' %}source{% endinlinecompile %}"""
            )
            self.assertEqual(
                template.render(Context({})),
                "compiled",
            )

            mocked_get_compiler_by_name.assert_called_with("sass")
            mocked_compiler.compile_source.assert_called_with("source")
示例#35
0
文件: base.py 项目: yellowcap/django
    def load_template(self, template_name, template_dirs=None):
        source, display_name = self.load_template_source(
            template_name, template_dirs)
        origin = make_origin(
            display_name, self.load_template_source,
            template_name, template_dirs)

        try:
            template = get_template_from_string(source, origin, template_name)
        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
示例#36
0
    def test_CSRF_token_GET_form(self):
        form_helper = FormHelper()
        form_helper.form_method = 'GET'
        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)

        c = Context({
            'form': TestForm(),
            'form_helper': form_helper,
            'csrf_token': _get_new_csrf_key()
        })
        html = template.render(c)

        self.assertFalse(
            "<input type='hidden' name='csrfmiddlewaretoken'" in html)
示例#37
0
文件: views.py 项目: cash2one/tender
def test(request):

    class CaptchaTestForm(forms.Form):
        subject = forms.CharField(max_length=100)
        sender = forms.EmailField()
        captcha = CaptchaField(help_text='asdasd')

    passed = False
    if request.POST:
        form = CaptchaTestForm(request.POST)
        if form.is_valid():
            passed = True
    else:
        form = CaptchaTestForm()

    t = loader.get_template_from_string(TEST_TEMPLATE)
    return HttpResponse(t.render(RequestContext(request, dict(passed=passed, form=form))))
示例#38
0
 def load_template(self, template_name, template_dirs=None):
     template, origin = self.find_template(template_name, template_dirs)
     if hasattr(template, 'render'):
         raise ImproperlyConfigured("Cannot handle loaders that prerender")
     template = self._process(template)
     try:
         template = get_template_from_string(template, origin,
                                             template_name)
     except TemplateDoesNotExist:
         # from django.template.loader.cached.Loader:
         # 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.
         return template, origin
     return template, None
示例#39
0
    def test_meta_extra_fields_with_missing_fields(self):
        form = FormWithMeta()
        # We remove email field on the go
        del form.fields['email']

        form_helper = FormHelper()
        form_helper.layout = Layout(
            'first_name',
        )

        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': form, 'form_helper': form_helper})
        html = template.render(c)
        self.assertFalse('email' in html)
示例#40
0
    def test_crispy_filter_with_formset(self):
        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {{ testFormset|crispy }}
        """)

        TestFormset = formset_factory(TestForm, extra=4)
        testFormset = TestFormset()

        c = Context({'testFormset': testFormset})
        html = template.render(c)

        self.assertEqual(html.count('<form'), 0)
        # Check formset management form
        self.assertTrue('form-TOTAL_FORMS' in html)
        self.assertTrue('form-INITIAL_FORMS' in html)
        self.assertTrue('form-MAX_NUM_FORMS' in html)
示例#41
0
    def test_invalid_unicode_characters(self):
        # Adds a BooleanField that uses non valid unicode characters "ñ"
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                'españa'
            )
        )

        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        settings.CRISPY_FAIL_SILENTLY = False
        self.assertRaises(Exception, lambda:template.render(c))
        del settings.CRISPY_FAIL_SILENTLY
def test_custom_error_message(request):
    class CaptchaTestForm(forms.Form):
        captcha = CaptchaField(
            help_text='asdasd',
            error_messages=dict(invalid='TEST CUSTOM ERROR MESSAGE'))

    passed = False
    if request.POST:
        form = CaptchaTestForm(request.POST)
        if form.is_valid():
            passed = True
    else:
        form = CaptchaTestForm()

    t = loader.get_template_from_string(TEST_TEMPLATE)
    return HttpResponse(
        t.render(RequestContext(request, dict(passed=passed, form=form))))
示例#43
0
文件: cached.py 项目: zraurum/django
 def load_template(self, template_name, template_dirs=None):
     key = self.cache_key(template_name, template_dirs)
     try:
         template = self.template_cache[key]
     except KeyError:
         template, origin = self.find_template(template_name, template_dirs)
         if not hasattr(template, 'render'):
             try:
                 template = get_template_from_string(
                     template, origin, template_name)
             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.
                 return template, origin
         self.template_cache[key] = template
     return template, None
示例#44
0
    def test_example(self):
        template = get_template_from_string("""
            {% load bootstrap_pagination %}
            {% bootstrap_paginate page_obj range=10 %}
        """)

        objects = ["obj%02x" % idx for idx in range(30)]

        paginator = Paginator(objects, 10)

        c = Context({
            'page_obj': paginator.page(2),
            'request': django.http.HttpRequest()
        })
        html = lxml.html.fragment_fromstring(template.render(c))
        self.assertEqual(html.get('class'), 'pagination')
        self.assertEqual(
            html.cssselect('[title=\"Current Page\"]')[0].text.strip(), '2')
示例#45
0
    def auth_html(self):
        app_id = backend_setting(self, self.SETTINGS_KEY_NAME)
        ctx = {
            'FACEBOOK_APP_ID': app_id,
            'FACEBOOK_EXTENDED_PERMISSIONS': ','.join(
                backend_setting(self, self.SCOPE_VAR_NAME)
            ),
            'FACEBOOK_COMPLETE_URI': self.redirect_uri,
            'FACEBOOK_APP_NAMESPACE': APP_NAMESPACE or app_id
        }

        try:
            fb_template = loader.get_template(LOCAL_HTML)
        except TemplateDoesNotExist:
            fb_template = loader.get_template_from_string(REDIRECT_HTML)
        context = RequestContext(self.request, ctx)

        return fb_template.render(context)
示例#46
0
 def myrender(self, user, label_for, rendered_cb):
     u = '''
         {%% load displayuser %%}
         <td>
         <div style="float: left; margin-top: 15px;">
         %(cb)s
         </div>
         {%% displayuser user %%}
         </td>
         ''' % {
         'name': user.get_full_name(),
         'email': user.email,
         'lbl': label_for,
         'cb': rendered_cb
     }
     context = Context()
     context['user'] = user
     return loader.get_template_from_string(u).render(context)
示例#47
0
def render_from_string(source, context={}):
    from django.template import Context
    from django.template import loader
    from django.template.loader import get_template

    _content = ''
    tplate = source
    if (misc.isString(source)):
        tplate = loader.get_template_from_string(source)
    toks1 = ObjectTypeName.typeClassName(tplate).split('.')
    toks2 = 'django.template.Template'.split('.')
    cnt = 0
    for t in toks2:
        if (t in toks1):
            cnt += 1
    if (cnt == len(toks2)):
        _content = tplate.render(Context(context, autoescape=False))
    return _content
示例#48
0
    def test_context_pollution(self):
        class ExampleForm(forms.Form):
            comment = forms.CharField()

        form = ExampleForm()
        form2 = TestForm()

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {{ form.as_ul }}
            {% crispy form2 %}
            {{ form.as_ul }}
        """)
        c = Context({'form': form, 'form2': form2})
        html = template.render(c)

        self.assertEqual(html.count('name="comment"'), 2)
        self.assertEqual(html.count('name="is_company"'), 1)
示例#49
0
    def test_as_uni_form_set(self):
        """The test formset should have two forms (extra=2)"""

        # build the context
        c = Context({'formset': TestFormset()})

        # Simple formset template
        template = get_template_from_string("""
{% load uni_form_tags %}
{{ formset|as_uni_form_set }}
        """)

        # render the formset template
        html = template.render(c)

        self.assertTrue("<td>" not in html)
        self.assertTrue("id_form-0-is_company" in html)
        self.assertTrue("id_form-1-is_company" in html)
示例#50
0
  def render(self, name, value, attrs=None):
    """Render plain text input or widget with extra fields.

    Extra fields are 'required' and 'has_comment'.
    """

    # plain text area
    output = super(ShortTextInput, self).render(name, value, attrs)

    # add 'required' and 'has_comment' fields
    context = dict(name=name, is_required=self.is_required,
                   has_comment=self.has_comment)
    template = loader.get_template_from_string(REQUIRED_COMMENT_TPL)
    rendered = template.render(context=loader.Context(dict_=context))
    output =  rendered + output

    output = '<fieldset>' + output + '</fieldset>'
    return output
示例#51
0
    def test_layout_composition(self):
        form_helper = FormHelper()
        form_helper.add_layout(
            Layout(
                Layout(
                    MultiField(
                        "Some company data",
                        'is_company',
                        'email',
                        css_id="multifield_info",
                    ), ),
                Column(
                    'first_name',
                    # 'last_name', Missing a field on purpose
                    css_id="column_name",
                    css_class="columns",
                ),
                ButtonHolder(Submit('Save', 'Save',
                                    css_class='button white'), ),
                Div(
                    'password1',
                    'password2',
                    css_id="custom-div",
                    css_class="customdivs",
                )))

        template = loader.get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': TestForm(), 'form_helper': form_helper})
        html = template.render(c)

        self.assertTrue('multiField' in html)
        self.assertTrue('formColumn' in html)
        self.assertTrue('id="multifield_info"' in html)
        self.assertTrue('id="column_name"' in html)
        self.assertTrue('class="formColumn columns"' in html)
        self.assertTrue('class="buttonHolder">' in html)
        self.assertTrue('input type="submit"' in html)
        self.assertTrue('name="Save"' in html)
        self.assertTrue('id="custom-div"' in html)
        self.assertTrue('class="customdivs"' in html)
        self.assertFalse('last_name' in html)
示例#52
0
 def test_contact_placeholder(self):
     tpl = ("{% load pages_tags %}{% contactplaceholder contact %}")
     
     template = get_template_from_string(tpl)
     page = self.new_page({'contact': 'hello'})
     context = Context({'current_page': page})
     
     import logging
     logger = logging.getLogger("pages")
     lvl = logger.getEffectiveLevel()
     logger.setLevel(logging.ERROR)
     
     with self.assertRaises(ValueError): 
         self.assertEqual(template.render(context), 'hello')
         
     logger.setLevel(lvl)
         
     context = Context({'current_page': page, 'request':get_request_mock()})
     self.assertTrue("<form" in template.render(context))
示例#53
0
    def load_template(self, template_name, template_dirs=None):
        if isinstance(template_name, Template):
            return (template_name, '')
        # require that templates loaded via this loader start with 'pages:'
        if not template_name.startswith('pages:'):
            raise TemplateDoesNotExist(template_name)

        db_template_name = template_name.replace('pages:', '', 1)
        try:
            template = PageTemplate.objects.get(name__exact=db_template_name)
        except PageTemplate.DoesNotExist:
            raise TemplateDoesNotExist(template_name)

        if template.is_path:
            template = get_template(template.path)
        else:
            template = get_template_from_string(template.content)

        return (template, template_name)
示例#54
0
文件: tests.py 项目: potar/lfs
    def test_ga_ecommerce_tracking(self):
        """
        """
        shop = Shop.objects.get(pk=1)
        shop.google_analytics_id = ""
        shop.ga_site_tracking = False
        shop.ga_ecommerce_tracking = False
        shop.save()

        session = SessionStore()

        rf = RequestFactory()
        request = rf.get('/')
        request.session = session

        template = get_template_from_string(
            """{% load lfs_tags %}{% google_analytics_ecommerce %}""")

        content = template.render(Context({"request": request}))
        self.failIf(content.find("pageTracker") != -1)

        # Enter a google_analytics_id
        shop.google_analytics_id = "UA-XXXXXXXXXX"
        shop.save()

        # But this is not enough
        content = template.render(Context({"request": request}))
        self.failIf(content.find("pageTracker") != -1)

        # It has to be activated first
        shop.ga_ecommerce_tracking = True
        shop.save()

        # But this is still not enough
        content = template.render(Context({"request": request}))
        self.failIf(content.find("pageTracker") != -1)

        # There has to be an order within the session
        session["order"] = Order()

        # Now it works and "pageTracker" is found
        content = template.render(Context({"request": request}))
        self.failIf(content.find("pageTracker") == -1)
示例#55
0
    def test_uni_form_helper_generic_attributes(self):

        form_helper = FormHelper()
        form_helper.form_id = 'this-form-rocks'
        form_helper.form_class = 'forms-that-rock'
        form_helper.form_method = 'GET'

        c = Context({'form': TestForm(), 'form_helper': form_helper})
        template = get_template_from_string("""
{% load uni_form_tags %}
{% uni_form form form_helper %}
        """)
        html = template.render(c)

        good_response = """<form action="" class="uniForm forms-that-rock" method="POST" id="this-form-rocks" >"""

        self.assertTrue(
            '<form action="" class="uniForm forms-that-rock" method="GET" id="this-form-rocks" >'
            in html)
示例#56
0
 def load_template(self, template_name, template_dirs=None):
     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
     elif template_tuple is None:
         template, origin = self.find_template(template_name, template_dirs)
         if not hasattr(template, 'render'):
             try:
                 template = get_template_from_string(template, origin, template_name)
             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]
示例#57
0
    def load_template(self, template_name, template_dirs=None):
        key = template_name
        if template_dirs:
            # If template directories were specified, use a hash to differentiate
            key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])

        if key not in self.template_cache:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = get_template_from_string(template, origin, template_name)
                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.
                    return template, origin
            self.template_cache[key] = template
        return self.template_cache[key], None
示例#58
0
    def test_CSRF_token_POST_form(self):
        form_helper = FormHelper()
        template = get_template_from_string(u"""
            {% load uni_form_tags %}
            {% uni_form form form_helper %}
        """)

        # The middleware only initializes the CSRF token when processing a real request
        # So using RequestContext or csrf(request) here does not work.
        # Instead I set the key `csrf_token` to a CSRF token manually, which `csrf_token` tag uses
        c = Context({
            'form': TestForm(),
            'form_helper': form_helper,
            'csrf_token': _get_new_csrf_key()
        })
        html = template.render(c)

        self.assertTrue(
            "<input type='hidden' name='csrfmiddlewaretoken'" in html)
示例#59
0
    def render(self, name, value, attrs=None, choices=()):
        output = []

        value = force_str(value) or ''

        attrs = self.build_attrs(attrs)
        t = loader.get_template_from_string(self.output_html)

        for id, label in list(chain(self.choices, choices)):
            check = lambda v: force_str(v) in value
            radio = RadioInput(attrs, check_test=check)
            output.append(
                t.render(
                    loader.Context({
                        "field": radio.render(name, id),
                        "label": mark_safe("%s" % label)
                    })))

        return mark_safe("&nbsp;&nbsp;&nbsp;&nbsp;".join(output))
示例#60
0
    def test_layout_uses_instance_for_missing_fields(self):
        class FormWithMeta(TestForm):
            class Meta:
                fields = ('email', 'first_name', 'last_name')

        form = FormWithMeta()
        # We remove email field on the go
        del form.fields['email']

        form_helper = FormHelper()
        form_helper.add_layout(Layout('first_name', ))

        template = get_template_from_string(u"""
            {% load crispy_forms_tags %}
            {% crispy form form_helper %}
        """)
        c = Context({'form': form, 'form_helper': form_helper})
        html = template.render(c)
        self.assertFalse('email' in html)