Пример #1
0
    def test_gravatar_img(self):
        # Some defaults for testing
        email = 'matt@automattic.com'
        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)
Пример #2
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')
Пример #3
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')
Пример #4
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>')
 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)
Пример #6
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)
Пример #7
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))
Пример #8
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)
Пример #9
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'
Пример #10
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
Пример #11
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
Пример #12
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))
Пример #13
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))
Пример #14
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
Пример #15
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)
Пример #16
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)
Пример #17
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)
Пример #18
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)
Пример #19
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)
Пример #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')
Пример #21
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)
Пример #22
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
Пример #23
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)
Пример #24
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)
Пример #25
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)
Пример #26
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
Пример #27
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')
Пример #28
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')
Пример #29
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>""",
                )
Пример #30
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")