Example #1
0
    def test_invalid_input(self):
        context = Context({'email': None})

        t = Template("{% load gravatar %}{% gravatar email %}")
        rendered = t.render(context)

        self.assertEqual("", rendered, "Invalid input should return empty result")
Example #2
0
    def test_docutils(self):
        try:
            import docutils
        except ImportError:
            docutils = None

        rest_content = """Paragraph 1

Paragraph 2 with a link_

.. _link: http://www.example.com/"""

        t = Template("{{ rest_content|restructuredtext }}")
        rendered = t.render(Context(locals())).strip()
        if docutils:
            # Different versions of docutils return slightly different HTML
            try:
                # Docutils v0.4 and earlier
                self.assertEqual(
                    rendered,
                    """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""",
                )
            except AssertionError, e:
                # Docutils from SVN (which will become 0.5)
                self.assertEqual(
                    rendered,
                    """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""",
                )
Example #3
0
    def test_extras(self):
        link = CustomLink.objects.create(publication_id=1, description='Test', url='http://test.com')
        link.save()

        publication = Publication.objects.get(pk=1)
        lists = List.objects.filter(list__iexact='highlights')

        self.assertEqual(len(lists), 1)

        # add publication to list
        publication.lists.add(lists[0])

        # render list
        tpl = Template("""
			{% load publication_extras %}
			{% get_publication 1 %}
			{% get_publication_list 'highlights' 'publications/publications_with_thumbnails.html' %}
			{% get_publication 10 %}
			{% get_publications %}
			""")

        self.assertGreater(len(tpl.render(RequestContext(HttpRequest())).strip()), 0)

        # tex_parse is used to replace simple LaTeX code in publication titles
        self.assertEqual(tex_parse(u'$L_p$-spherical'), u'L<sub>p</sub>-spherical')
        self.assertEqual(tex_parse(u'$L^2$-spherical'), u'L<sup>2</sup>-spherical')
Example #4
0
    def test_gravatar_img(self):
        # Some defaults for testing
        email = '*****@*****.**'
        alt_text = 'some alt text'
        css_class = 'gravatar-thumb'
        size = 250

        # Build context
        context = Context({
            'email': email,
            'size': size,
            'alt_text': alt_text,
            'css_class': css_class,
        })

        # Default behavior
        t = Template("{% load gravatar %}{% gravatar email %}")
        rendered = t.render(context)

        self.assertTrue(escape(get_gravatar_url(email)) in rendered)
        self.assertTrue('class="gravatar"' in rendered)
        self.assertTrue('alt=""' in rendered)

        t = Template("{% load gravatar %}{% gravatar email size alt_text css_class %}")
        rendered = t.render(context)

        self.assertTrue('width="%s"' % (size,) in rendered)
        self.assertTrue('height="%s"' % (size,) in rendered)
        self.assertTrue('alt="%s"' % (alt_text,) in rendered)
        self.assertTrue('class="%s"' % (css_class,) in rendered)
Example #5
0
def empty_urlconf(request):
    "Create an empty URLconf 404 error response."
    t = Template(EMPTY_URLCONF_TEMPLATE, name='Empty URLConf template')
    c = Context({
        'project_name': settings.SETTINGS_MODULE.split('.')[0]
    })
    return HttpResponse(t.render(c), mimetype='text/html')
Example #6
0
    def test_result_list_with_allow_tags(self):
        """
        Test for deprecation of allow_tags attribute
        """
        new_parent = Parent.objects.create(name='parent')
        for i in range(2):
            Child.objects.create(name='name %s' % i, parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, custom_site)

        def custom_method(self, obj=None):
            return 'Unsafe html <br />'
        custom_method.allow_tags = True

        # Add custom method with allow_tags attribute
        m.custom_method = custom_method
        m.list_display = ['id', 'name', 'parent', 'custom_method']

        cl = ChangeList(request, Child, *get_changelist_args(m))
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        custom_field_html = '<td class="field-custom_method">Unsafe html <br /></td>'
        self.assertInHTML(custom_field_html, table_output)
Example #7
0
    def test_get_fieldsets_legacy(self):
        """Testing the get_fieldsets template filter with legacy fieldsets"""
        class MyForm(Form):
            class Meta:
                fieldsets = (
                    {
                        'title': 'Test 1',
                        'description': 'This is test 1',
                        'fields': ('field_1', 'field_2'),
                    },
                    {
                        'description': 'This is test 2',
                        'fields': ('field_3', 'field_4'),
                    }
                )

        t = Template(
            '{% load djblets_forms %}'
            '{% for title, fieldset in form|get_fieldsets %}'
            'Title: {{title}}\n'
            'Description: {{fieldset.description}}\n'
            'Fields: {{fieldset.fields|join:","}}\n'
            '{% endfor %}'
        )

        self.assertEqual(
            t.render(Context({
                'form': MyForm(),
            })),
            'Title: Test 1\n'
            'Description: This is test 1\n'
            'Fields: field_1,field_2\n'
            'Title: None\n'
            'Description: This is test 2\n'
            'Fields: field_3,field_4\n')
Example #8
0
  def get(self):
    (forum, siteroot, tmpldir) = forum_siteroot_tmpldir_from_url(self.request.path_info)
    if not forum or forum.is_disabled:
      return self.error(HTTP_NOT_FOUND)
 
    feed = feedgenerator.Atom1Feed(
      title = forum.title or forum.url,
      link = siteroot + "rssall",
      description = forum.tagline)
  
    posts = Post.gql("WHERE forum = :1 AND is_deleted = False ORDER BY created_on DESC", forum).fetch(25)
    for post in posts:
      topic = post.topic
      title = topic.subject
      link = siteroot + "topic?id=" + str(topic.key().id())
      msg = post.message
      # TODO: a hack: using a full template to format message body.
      # There must be a way to do it using straight django APIs
      name = post.user_name
      if name:
        t = Template("<strong>{{ name }}</strong>: {{ msg|striptags|escape|urlize|linebreaksbr }}")
      else:
        t = Template("{{ msg|striptags|escape|urlize|linebreaksbr }}")
      c = Context({"msg": msg, "name" : name})
      description = t.render(c)
      pubdate = post.created_on
      feed.add_item(title=title, link=link, description=description, pubdate=pubdate)
    feedtxt = feed.writeString('utf-8')
    self.response.headers['Content-Type'] = 'text/xml'
    self.response.out.write(feedtxt)
 def _test_templatetag(self, crop_field, options={}):
     option_str = ' '.join(['%s=%s' % (option, value)
                            for option, value in options.items()])
     tmpl = 'cropped_thumbnail image "%s" %s' % (crop_field, option_str)
     tmpl = '{% load cropping %}{% ' + tmpl + ' %}'
     t = Template(tmpl)
     return t.render(self.context)
Example #10
0
def table2htmlDjango(table, writecolnames=True, writerownames=False, safe=False):
    safe = "|safe" if safe else ""
    if table.rowNamesRequired == True:
        writerownames = True
    t = Template("""<table class="display">
        {% if writecolnames %}
        <thead>
            {% if writerownames %}
                <th></th>
            {% endif %}
            {% for header in table.getColumns %}
                <th>{{header}}</th>
            {% endfor %}
        </thead>
        {% endif %}
        <tbody>
            {% for row in table %}
                <tr>
                    {% if writerownames %}
                        <td>{{row.row}}</td>
                    {% endif %}
                    {% for col in row %}
                        <td>{{col"""+safe+"""|default_if_none:"-" }}</td>
                    {% endfor %}
                </tr>
            {% endfor %}
       </tbody>
    </table>""")
    c = Context({"table": table, 'writecolnames':writecolnames, 'writerownames':writerownames})
    return t.render(c)
Example #11
0
    def test_xss_error_messages(self):
        ###################################################
        # Tests for XSS vulnerabilities in error messages #
        ###################################################

        # The forms layer doesn't escape input values directly because error messages
        # might be presented in non-HTML contexts. Instead, the message is just marked
        # for escaping by the template engine. So we'll need to construct a little
        # silly template to trigger the escaping.
        from django.template import Template, Context
        t = Template('{{ form.errors }}')

        class SomeForm(Form):
            field = ChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': '<script>'})
        self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')

        class SomeForm(Form):
            field = MultipleChoiceField(choices=[('one', 'One')])

        f = SomeForm({'field': ['<script>']})
        self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')

        from regressiontests.forms.models import ChoiceModel

        class SomeForm(Form):
            field = ModelMultipleChoiceField(ChoiceModel.objects.all())

        f = SomeForm({'field': ['<script>']})
        self.assertHTMLEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>')
Example #12
0
    def test_oembed_tag(self, devour):
        tpl = Template('{% load oembed_tags %}{% oembed %}http://foo.com{% endoembed %}')
        devour.return_value = 'FOO'
        result = tpl.render(Context())

        self.assertEqual('FOO', result)
        devour.assert_called_with('http://foo.com', html=True, maxwidth=None, maxheight=None)
Example #13
0
def non_token_view_using_request_processor(request):
    """
    A view that doesn't use the token, but does use the csrf view processor.
    """
    context = RequestContext(request, processors=[csrf])
    template = Template("")
    return HttpResponse(template.render(context))
Example #14
0
    def test_oembed_text_tag_with_size(self, devour):
        tpl = Template('{% load oembed_tags %}{% oembed_text 100x900 %}http://foo.com{% endoembed_text %}')
        devour.return_value = 'FOO'
        result = tpl.render(Context())

        self.assertEqual('FOO', result)
        devour.assert_called_with('http://foo.com', html=False, maxwidth=100, maxheight=900)
Example #15
0
    def test_oembed_text_filter_with_size(self, devour):
        tpl = Template('{% load oembed_tags %}{{ content|oembed_text:"100x200" }}')
        devour.return_value = 'FOO'
        result = tpl.render(Context({'content': 'http://foo.com'}))

        self.assertEqual('FOO', result)
        devour.assert_called_width('http://foo.com', html=True, maxwidth=100, maxheight=200)
Example #16
0
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried                           # empty URLconf
            or (request.path == '/'
                and len(tried) == 1             # default URLconf
                and len(tried[0]) == 1
                and tried[0][0].app_name == tried[0][0].namespace == 'admin')):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html')
Example #17
0
def index(request):

	p = request.GET.get('p')
	#if p is not None:
	#    return HttpResponse(p)
	#else:
	#    return HttpResponse("No hay p ")
	
	#from django.template import Context, Template
	#t = Template("Mi nombre es {{ nombre }}.")
	#c = Context({"nombre": p})
	#return HttpResponse(t.render(c))

	from django.template import Context, Template
	t = Template("Mi nombre es {{ nombre }}.")
	c = Context({"nombre": p})
	#html = open("/1.html")
	#return HttpResponse(html)
	
	#fp = open('D:/Programas Facultad/Diego G/workspace/github/ChiettiRepo/Chieti/proj2/temaplates/1.html')
	fp = open('./proj2/1.html')
	t = Template(fp.read())
	fp.close()
	html = t.render(Context())
	return HttpResponse(html)
Example #18
0
    def handle(self, *args, **options):

        tpl = Template("""
title:{{object.title}} 
subtitle:{{object.sub_title}}
slug:{{object.slug}}
featured:{{object.featured}}
status:{{object.status}}
add_date:{{object.add_date}}
pub_date:{{object.pub_date}}
mod_date:{{object.mod_date}}
project_date:{{object.project_date}}


#{{object.title}}
##{{object.sub_title}}
{{object.body}}

todo
images = models.ManyToManyField(Image, blank=True, through=ArticleImage)
files = models.ManyToManyField(File, blank=True)
vimeo = models.URLField(max_length=100, blank=True, null=True)
tags = TaggableManager(blank=True, through=TaggedArticle)


            """)
        for article in Article.objects.all():
            c = Context({"object": article})
            print tpl.render(c)
Example #19
0
 def test_included_tokenlist_rendering(self):
     field_placement = (
         { 'field': "small-12 columns"
         , 'label': "small-12 medium-2 columns"
         , 'value': "small-12 medium-10 columns"
         })
     field = (
         { 'field_placement':        field_placement
         , 'field_label':            "Permissions"
         , 'field_placeholder':      "(user permissions)"
         , 'field_name':             "User_permissions"
         , 'field_edit_value':       ["VIEW", "CREATE", "UPDATE", "DELETE", "CONFIG", "ADMIN"]
         , 'field_render_object':    get_field_tokenset_renderer().label_edit()
         })
     template = Template("{% include field.field_render_object %}")
     context  = Context({ 'render_object': get_field_tokenset_renderer().label_edit(), 'field': field})
     rendered = template.render(context)
     rendered = re.sub(r'\s+', " ", rendered)
     self.assertIn('''<div class="small-12 columns">''',                             rendered)
     self.assertIn('''<div class="row view-value-row">''',                           rendered)
     self.assertIn(
         '''<div class="view-label small-12 medium-2 columns"> '''+
           '''<span>Permissions</span> '''+
         '''</div>''',
         rendered
         )
     self.assertIn('''<div class="view-value small-12 medium-10 columns">''',        rendered)
     self.assertIn('''<input type="text" size="64" name="User_permissions" ''',      rendered)
     self.assertIn(       '''placeholder="(user permissions)"''',                    rendered)
     self.assertIn(       '''value="VIEW CREATE UPDATE DELETE CONFIG ADMIN"/>''',    rendered)
     return
Example #20
0
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if not tried:
            # tried exists but is an empty list. The URLconf must've been empty.
            return empty_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path_info[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': smart_str(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), mimetype='text/html')
Example #21
0
def render_email(user, request):
    """Render an email and return its subject and body.

    This function takes as arguments a QueryDict and a user. The user will
    serve as the target of the mail. The QueryDict should contain a `text` and
    `subject` attribute that will be used as the body and subject of the mail
    respectively.

    The email can optionally be customized with user information. If the user
    has provided any one of the following variables:

        {{ full_name }}, {{ first_name }}, {{ last_name }}, {{ email }}

    then they will be rendered appropriately.
    """
    c = Context({'full_name': user.realname,
                 'first_name': user.first_name,
                 'last_name': user.last_name,
                 'email': user.email, })

    # Render the mail body
    t = Template(request['text'])
    body = t.render(c)

    # Render the mail subject
    t = Template(request['subject'])
    subject = t.render(c)
    return subject, body
Example #22
0
    def json(self):
        """
        generate JSON for the post/comment object, intended to be returned via AJAX
        """

        # Use the implicit template formatting rather than the __str__
        # formatting, which is default if we were to return a formatted string.
        json_template = Template(
            """
            {
                "author":
                {
                    "email": "{{ email }}",
                    "first_name": "{{ first_name }}",
                    "last_name": "{{ last_name }}"
                },
                "date_posted": "{{ date_posted }}",
                "time_stamp": "{{ time_stamp }}",
                "message": "{{ message }}"
            }"""
        )
        ctx = Context(
            {
                "email": self.author.user.email,
                "first_name": self.author.user.first_name,
                "last_name": self.author.user.last_name,
                "date_posted": self.date_posted,
                "time_stamp": self.time_stamp(),
                "message": self.message,
            }
        )
        return json_template.render(ctx)
Example #23
0
    def get_traceback_html(self):
        "Return HTML code for traceback."

        if issubclass(self.exc_type, TemplateDoesNotExist):
            self.template_does_not_exist = True
        if self._template:
            self.get_template_exception_info()

        frames = self.get_traceback_frames()

        unicode_hint = ''
        if issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_unicode(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
        t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
        c = Context({
            'exception_type': self.exc_type.__name__,
            'exception_value': smart_unicode(self.exc_value, errors='replace'),
            'unicode_hint': unicode_hint,
            'frames': frames,
            'lastframe': frames[-1],
            'request': self.request,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
        })
        return t.render(c)
Example #24
0
 def student_view(self, context=None):
     """
     The primary view of the ContentXBlock, shown to students
     when viewing courses.
     """
     if self.contnet_type == "content":
         result = Fragment()
         url = "public/html/"+self.short_name+".html"
         fragment = Fragment(self.resource_string(url))
         html_template = Template(self.resource_string("templates/student_view.html"))
         html_context = Context({"fragment": fragment}) 
         html_str = html_template.render(html_context)
         result.add_content(html_str)
         return result
     elif self.contnet_type == "topnav":
         html_context = Context({"source_link": self.source_link, 
                                 "prev_link": self.prev_link, 
                                 "prev_name": self.prev_name, 
                                 "toc_link": self.toc_link, 
                                 "next_link": self.next_link, 
                                 "next_name": self.next_name, 
                                 })
         html_template = Template(self.resource_string("templates/student_view_topnav.html"))
         fragment = Fragment(html_template.render(html_context))
         return fragment
     elif self.contnet_type == "header":
         return
     elif self.contnet_type == "footer":
         return
Example #25
0
 def string_template_replace(self, text, context_dict):
     from django.template import Context, Template, TemplateSyntaxError
     try:
         t = Template(text)
         return t.render(Context(context_dict))
     except TemplateSyntaxError:
         return text
Example #26
0
def completed_jobs(sample_data):
    """returns a list of buildapi completed jobs"""
    with open(os.path.join(base_dir, "finished.json")) as f:
        content = f.read()
        t = Template(content)
        c = Context({"base_dir": base_dir})
        return json.loads(t.render(c))
Example #27
0
	def buildPage(self, path):
		
		outputPath = os.path.join(self.paths['build'], path)
	
		try:
			os.makedirs(os.path.dirname(outputPath))
		except OSError:
			pass
		
		f = codecs.open(os.path.join(self.paths['pages'], path), 'r', 'utf8')
		source = f.read()
		f.close()
		
		pageContext, data = render.process(path, source)
		
		t = Template(data)
		f = codecs.open(outputPath, 'w', 'utf8')
		
		prefix = '/'.join(['..' for i in xrange(len(path.split('/')) - 1)])
	
		context = {
			'STATIC_URL': os.path.join(prefix, 'static'),
			'ROOT_URL': prefix,
			'CACTUS': {
				'path': path,
				'pages': self._pages
			}
		}
	
		context.update(pageContext)
	
		f.write(t.render(Context(context)))
		f.close()
		
		self.log("  * Built %s" % (path))
Example #28
0
def test_render_table_should_support_template_argument():
    table = CountryTable(MEMORY_DATA, order_by=('name', 'population'))
    template = Template('{% load django_tables2 %}'
                        '{% render_table table "dummy.html" %}')
    request = build_request('/')
    context = RequestContext(request, {'table': table})
    assert template.render(context) == 'dummy template contents\n'
Example #29
0
 def get_context_data(self, **kwargs):
     context = super(PrintRegistryTerm, self).get_context_data(**kwargs)
     movement = get_object_or_404(AssetMovement, pk=kwargs['mov_id'])
     registry = movement.origin
     term = registry.term_model
     term_text = term.term_text
     
     self.pdf_file_name = term.get_term_type_display()
     
     extra_context = {
         "asset_code"           : registry.asset.asset_code,
         "asset_type"           : registry.asset.asset_type.description,
         "asset_description"    : registry.asset.description        if term.term_type != 'C' else registry.old_description,
         "registry_date"        : registry.registry_date,
         "registry_annotation"  : registry.annotation,
         "transfer_from_unit"   : registry.from_unit.name           if term.term_type == 'T'        else None,
         "transfer_to_unit"     : registry.to_unit.name             if term.term_type == 'T'        else None,
         "transfer_from_chief"  : registry.from_chief.name          if term.term_type == 'T'        else None,
         "transfer_to_chief"    : registry.to_chief.name            if term.term_type == 'T'        else None,
         "writedown_cause"      : registry.get_down_cause_display() if term.term_type == 'W'        else None,
         "asset_old_value"      : registry.old_value                if term.term_type in ('C', 'D') else None,
         "asset_old_description": registry.old_description          if term.term_type == 'C'        else None,
         "depreciation_value"   : registry.depreciation_value       if term.term_type == 'D'        else None,
         "asset_new_value"      : registry.new_value                if term.term_type in ('C', 'D') else None,
         "asset_new_description": registry.new_description          if term.term_type == 'C'        else None,}
     
     t = Template(term_text)
     term_text = t.render(Context(extra_context))
     extra_context['term_text'] = term_text
     extra_context['term'] = term
     extra_context['registry'] = registry
     
     context.update(extra_context)
     return context
Example #30
0
    def test_object_tools(self):
        autodiscover()
        context = template.Context({
            'model': User,
            'request': RequestFactory().get('/'),
        })
        t = Template("{% load object_tools_inclusion_tags %}{% object_tools \
                model request.user %}")

        # Anon user should not have any tools.
        result = t.render(context)
        expected_result = '\n'
        self.failUnlessEqual(result, expected_result)

        # User without permissions should not have any tools.
        user = User()
        user.save()
        context['request'].user = user
        result = t.render(context)
        expected_result = '\n'
        self.failUnlessEqual(result, expected_result)

        # Superuser should have tools.
        user.is_superuser = True
        user.save()
        result = t.render(context)
        expected_result = u'\n    <li><a href="/object-tools/auth/user/\
test_tool/" title=""class="historylink">Test Tool</a></li>\n\n    \
<li><a href="/object-tools/auth/user/test_media_tool/" title=""\
class="historylink"></a></li>\n\n'
        self.failUnlessEqual(result, expected_result)
Example #31
0
 def test_gets_dynamically_generated_value_from_key(self):
     example_dict_like = LazyDictLike()
     template = Template("{% load get_from_key %}{{ d|get_from_key:'foo' }}")
     self.assertEqual(
         template.render(Context({'d': example_dict_like})), 'foofoo')
Example #32
0
def render_context(template, context_key, context, **kwargs):
    return Template(template).render(Context({context_key: context}))
Example #33
0
 def test_store_stock_loads(self):
     Template('{% load store_stock %}').render(Context())
Example #34
0
 def test_cms_var_tag_from_context_variable(self):
     "cms_var tag accepts context variable as code argument"
     ctx = {'cms_var_code': 'test_var'}
     out = Template("{% load minicms %}foo{% cms_var cms_var_code %}baz").render(Context(ctx))
     self.assertEqual(out, 'foobarbaz')
Example #35
0
 def test_cms_var_tag_as_variable(self):
     "cms_var tag output can be assigned to context variable"
     out = Template("{% load minicms %}{% cms_var 'test_var' as context_var %}foo{{ context_var }}baz").render(Context())
     self.assertEqual(out, 'foobarbaz')
Example #36
0
 def test_cms_var_tag(self):
     "cms_var tag correctly renders CmsVariable value"
     out = Template("{% load minicms %}foo{% cms_var 'test_var' %}baz").render(Context())
     self.assertEqual(out, 'foobarbaz')
Example #37
0
 def get_snippet(self, context):
     """ Render and return snippet (use default django template system)
     """
     t = Template(self.snippet)
     return t.render(context)
Example #38
0
 def test_gets_existing_key_from_dictionary(self):
     example_dict = {'foo': 'bar'}
     template = Template("{% load get_from_key %}{{ d|get_from_key:'foo' }}")
     self.assertEqual(
         template.render(Context({'d': example_dict})), 'bar')
Example #39
0
 def test_adds_query_parameters_to_the_existing_ones(self):
     request  = RequestFake('parameter=value')
     template = Template("{% load add_query_parameter %}{% add_query_parameter request 'foo' 'bar' %}")
     self.assertEqual(
         template.render(Context({'request': request})),
         'foo=bar&parameter=value')
Example #40
0
 def test_fails_if_key_is_not_present(self):
     example_dict = {'foo': 'bar'}
     template = Template("{% load get_from_key %}{{ d|get_from_key:'qux' }}")
     self.assertEqual(
         template.render(Context({'d': example_dict})), '')
Example #41
0
def _render_template(string, context=None):
    context = context or {}
    context = Context(context)
    return Template(string).render(context=context)
Example #42
0
 def test_overwrites_query_parameters_if_they_exist(self):
     request  = RequestFake('parameter=value')
     template = Template("{% load add_query_parameter %}{% add_query_parameter request 'parameter' 'bar' %}")
     self.assertEqual(
         template.render(Context({'request': request})), 'parameter=bar')
Example #43
0
    def render(self, context):
        if self.is_variable:
            real_key = template.Variable(self.key).resolve(context)
        else:
            real_key = self.key

        if isinstance(self.template_name, template.Variable):
            real_tpl = self.template_name.resolve(context)
        else:
            real_tpl = self.template_name

        context['chunk_key'] = real_key
        if self.content_type == 'edit':
            context['tag'] = self.tag
        sources = dict(text=Chunk,
                       edit=Chunk,
                       image=Image,
                       media=Media,
                       group=Group)
        model = sources[self.content_type]

        obj = None
        # try to get cached object
        if self.cache_time > 0:
            cache_key = CACHE_PREFIX + self.content_type + get_language(
            ) + real_key
            obj = cache.get(cache_key)
        # otherwise get it from database
        if obj is None:
            if self.content_type == 'group':
                obj = model.objects.filter(key=real_key)
            else:
                try:
                    obj = model.objects.get(key=real_key)
                except model.DoesNotExist:
                    # this place we should create an empty object in database
                    obj = model(key=real_key)
                    if self.content_type == 'image':
                        # image object must exist, so save the stub picture
                        filename = join(dirname(__file__), '..', 'static',
                                        'chunks', 'stub.png')
                        with open(filename, 'r') as file:
                            obj.image.save(basename(filename),
                                           File(file),
                                           save=True)
                    else:
                        obj.content = real_key
                        obj.save()

            # cache the object
            if self.cache_time == 0:
                logger.debug("Don't cache %s" % (real_key, ))
            else:
                if self.cache_time is None or self.cache_time == 'None':
                    logger.debug("Caching %s for the cache's default timeout" %
                                 real_key)
                    cache.set(cache_key, obj)
                else:
                    logger.debug("Caching %s for %s seconds" %
                                 (real_key, str(self.cache_time)))
                    cache.set(cache_key, obj, int(self.cache_time))

        # Eventually we want to pass the whole context to the template so that
        # users have the maximum of flexibility of what to do in there.
        if self.with_template:
            new_ctx = template.Context(context)
            if hasattr(obj, 'content'):
                obj.content = Template(obj.content).render(new_ctx)
            new_ctx.update({'obj': obj})
            tpl = template.loader.get_template(real_tpl)
            return tpl.render(new_ctx)
        elif hasattr(obj, 'image'):
            return obj.image.url
        elif hasattr(obj, 'content'):
            return obj.content
        else:
            return None
Example #44
0
 def test_adds_query_parameters_when_there_are_none(self):
     request  = RequestFake('')
     template = Template("{% load add_query_parameter %}{% add_query_parameter request 'parameter' 'value' %}")
     self.assertEqual(
         template.render(Context({'request': request})), 'parameter=value')
 def render(self, path):
     request = RequestFactory().get(path)
     request.flag_conditions = get_flags()
     template = Template("{% load hmda_banners %}"
                         "{% hmda_outage_banner request %}")
     return template.render(Context({"request": request}))
Example #46
0
 def render(self, form, form_style, context):
     return Template(self.html).render(context)
Example #47
0
 def test_ifinstalled(self, app, result):
     template = Template(
         "{% load mezzanine_tags %}"
         f"{{% ifinstalled {app} %}}CONTENT{{% endifinstalled %}}")
     html = template.render(Context({}))
     assert ("CONTENT" in html) == result
 def test_template_shown_as_used(self):
     template = Template(
         "{% load component_tags %}{% component 'test_component' %}",
         name='root')
     templates_used = self.templates_used_to_render(template)
     self.assertIn('slotted_template.html', templates_used)
Example #49
0
    def getHTML(request):

        context = RequestContext(request, {})

        template = Template(
            """
      {% load i18n %}
      <table>
        <tr>
          <td style="vertical-align:top; padding: 15px">
            <button type="submit" class="btn btn-primary" id="import" onclick="import_show('{% trans "Import a spreadsheet" %}',null,true,uploadspreadsheetajax)" value="{% trans "import"|capfirst %}">{% trans "import"|capfirst %}</button>
          </td>
          <td style="padding: 15px 15px 0 15px">
            <p>{% trans "Import input data from a spreadsheet.</p><p>The spreadsheet must match the structure exported with the task above." %}</p>
          </td>
        </tr>
      </table>
      <script>
      var xhr = {abort: function () {}};

      var uploadspreadsheetajax = {
        url: '{{request.prefix}}/execute/launch/importworkbook/',
        success: function (data) {
          var el = $('#uploadResponse');
          el.html(data);
          if (el.attr('data-scrolled')!== "true") {
            el.scrollTop(el[0].scrollHeight - el.height());
          }
          $('#cancelbutton').html("{% trans 'Close' %}");
          $('#importbutton').hide();
          $("#animatedcog").css('visibility','hidden');
          $('#cancelimportbutton').hide();
          if (document.queryCommandSupported('copy')) {
            $('#copytoclipboard').show();
          }
          $("#grid").trigger("reloadGrid");
        },
        xhrFields: {
          onprogress: function (e) {
            var el = $('#uploadResponse');
            el.html(e.currentTarget.response);
            if (el.attr('data-scrolled')!== "true") {
              el.attr('data-scrolled', el[0].scrollHeight - el.height());
              el.scrollTop(el[0].scrollHeight - el.height());
            }
          }
        },
        error: function() {
          $('#cancelimportbutton').hide();
          $('#copytoclipboard').show();
          $("#animatedcog").css('visibility','hidden');
          $("#uploadResponse").scrollTop($("#uploadResponse")[0].scrollHeight);
        }
      };
      </script>
    """
        )
        return template.render(context)
        # A list of translation strings from the above
        translated = (
            _("import"),
            _("Import a spreadsheet"),
            _(
                "Import input data from a spreadsheet.</p><p>The spreadsheet must match the structure exported with the task above."
            ),
        )
def parse_template(value):
    return mark_safe(Template(value).render(Context()))
Example #51
0
 def test_kwargs(self):
     tpl = Template("""{% load i18n %}
         {% language 'nl'  %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
         {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}""")
     self.assertEqual(tpl.render(Context({})).strip().split(),
                      ['/vertaald/apo/', '/traduzidos/apo/'])
 def subject(self):
     if not self._subject:
         self._subject = Template(self.drip_base.subject_template).render(
             self.context)
     return self._subject
Example #53
0
 def validate_template(self, value):
     try:
         Template(value)
     except TemplateSyntaxError as e:
         raise forms.ValidationError(six.text_type(e))
Example #54
0
def fmWebDh(conn, cur, mdcode):
    """spdl, spzl, barcode, spcode, spname, dhamount, indhamount, statusconvert(prostatus), propacketqty, maxminstock, curstock, saletotal, indhamount_max, indhamount_min, saleweek1, saleweek2,saleweek3, saleweek4, cuxiao, curalloc]"""
    
    usercode = mdcode
    userid = theFmWebSql.getUserInfo(usercode)["UserId"]
    
    
    #sqlstr = "select mdcode, mdname, prodl_id, prodl, prozl_id, prozl, spcode, spname, suggest, suggest, status, packetqty1, maxval, minval, curqty, total_qty, yqmaxlimit, yqminlimit, week1_qty, week2_qty, week3_qty, week4_qty, cuxiao_1, allocqty, normalprice, assortment, barcode from dhalldata where assortment is not null and status < '5' and suggest > 0 and shelf > '-1' and dhtag='T' and mdcode='"+mdcode+"'"
   
    sqlstr = "select mdcode, mdname, prodl_id, prodl, prozl_id, prozl, spcode, spname, suggest, suggest, status, packetqty1, maxval, minval, curqty, total_qty, yqmaxlimit, yqminlimit, week1_qty, week2_qty, week3_qty, week4_qty, cuxiao_1, allocqty, normalprice, assortment, barcode from dhalldata where assortment is not null and status < '5' and suggest > 0 and shelf > '-1' and dhtag='T'  and mdcode='"+mdcode+"'"
    
    
    cur.execute(sqlstr)
    result=cur.fetchall()
    conn.commit()
    
    try:
        mdname = result[0][1]
        
        result1 = [ x for x in result if x[25] == 'youtu']
        
        result2 = [ x for x in result if x[25] == 'wutu' and x[2] != '05']
       
        result3 = [ x for x in result if x[25] == 'wutu' and x[2] == '05']
        
        
        
        
       
        
        result1_a = [ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result1]
        
       
        
        result2_a = [ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result2]
        
       
        
        result3_a =[ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result3]
        
       
        
        result12 = result1+ result2
        suggestlist = [x[8] for x in result12]
        
       
        totalsku = len(result1_a + result2_a)
        totalqty = reduce(lambda x, y: x+y, suggestlist)
        
        
        
        fp = open('d:/vcms/lib/py/mana1/templates/mana1/dh.html')
        t = Template(fp.read())
        fp.close()
        
        
        
        
        html=t.render(Context({'userid': userid, 'result':result1_a, 'result2':result2_a, 'result3':result3_a, 'totalsku':totalsku, 'totalqty':str(totalqty), 'mdname':mdname}))
        
        
    except:
        html=u'系统不能生成订货值'
        
    return html
Example #55
0
    def test_should_make_a_menu_link_as_active(self):
        html = "{% load menu %}{% is_active request.get_full_path 'home' %}"
        template = Template(html)
        context = Context({'request': {"get_full_path": "/"}})

        self.assertEqual("active", template.render(context))
Example #56
0
 def test_strings_only(self):
     t = Template("""{% load i18n %}
         {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
         {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""")
     self.assertEqual(t.render(Context({})).strip().split(),
                      ['/vertaald/', '/traduzidos/'])
Example #57
0
from django.core.mail import EmailMessage

os.environ["DJANGO_SETTINGS_MODULE"] = 'mysite.settings'
django.setup()

from grading.models import Assignment, Enrollment


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Send assessments using email for specified assignment.")
    parser.add_argument('assignment_id')
    args = parser.parse_args()

    assignment = Assignment.objects.get(pk=args.assignment_id)
    mail_template = Template(assignment.mail_body)
    subject = assignment.mail_subject

    for report in assignment.report_set.filter(mail_is_sent=False):
        enrollment = Enrollment.objects.get(course=assignment.course, student=report.student)
        if enrollment.is_active:
            print("Sending mail to %s" % report.student)
            context = Context({'student': report.student})
            body = mail_template.render(context)
            email = EmailMessage(subject=subject, body=body,
                                 to=[report.student.email],
                                 bcc=['*****@*****.**'])
            try:
                email.attach_file(report.report.path)
            except ValueError:
                print("Not including report for student %s" % report.student)
Example #58
0
    def should_make_a_menu_link_as_not_active(self):
        html = "{% is_active request.get_full_path 'home' %}"
        template = Template(html)
        context = Context({'request': {"get_full_path": "register"}})

        self.assertNotEqual("active", template.render(context))
Example #59
0
 def tag_test(self, template, context, output):
     t = Template('{% load notifications_tags %}'+template)
     c = Context(context)
     self.assertEqual(t.render(c), output)
 def test_adds_class(self):
     context = Context({'form': MyForm()})
     template = Template(
         '{% load addcss %} {{form.title|addcss:"my custom classes"}}')
     content = template.render(context)
     self.assertIn('class="my custom classes"', content)