def test_context(self): ctx = Context({'lang1':'nl', 'lang2':'pt-br'}) tpl = Template("""{% load i18n %} {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""") self.assertEqual(tpl.render(ctx).strip().split(), ['/vertaald/', '/traduzidos/'])
def login_protected_view(self, request): t = Template( "This is a login protected test using a method. " "Username is {{ user.username }}.", name="Login Method Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c))
def session_view(request): "A view that modifies the session" request.session["tobacconist"] = "hovercraft" t = Template("This is a view that modifies the session.", name="Session Modifying View Template") c = Context() return HttpResponse(t.render(c))
def test_result_list_editable_html(self): """ Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) # Test with list_editable fields m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, 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) # make sure that hidden fields are in the correct place hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id self.assertFalse(table_output.find(hiddenfields_div) == -1, 'Failed to find hidden fields in: %s' % table_output) # make sure that list editable fields are rendered in divs correctly editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />' self.assertFalse('<td>%s</td>' % editable_name_field == -1, 'Failed to find "name" list_editable field in: %s' % table_output)
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), content_type='text/html')
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': force_bytes(exception, errors='replace'), 'request': request, 'settings': get_safe_settings(), }) return HttpResponseNotFound(t.render(c), content_type='text/html')
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 djangocg.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})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> 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})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> 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})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>"<script>" is not a valid value for a primary key.</li></ul></li></ul>')
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))
def humanize_tester(self, test_list, result_list, method): # Using max below ensures we go through both lists # However, if the lists are not equal length, this raises an exception for test_content, result in zip(test_list, result_list): t = Template('{%% load humanize %%}{{ test_content|%s }}' % method) rendered = t.render(Context(locals())).strip() self.assertEqual(rendered, escape(result), msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result))
def permission_protected_view(self, request): t = Template( "This is a permission protected test using a method. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c))
def _permission_protected_view(request): "A simple view that is permission protected." t = Template( "This is a permission protected test. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c))
def csrf_failure(request, reason=""): """ Default view used when request fails CSRF protection """ from djangocg.middleware.csrf import REASON_NO_REFERER t = Template(CSRF_FAILURE_TEMPLATE) c = Context({'DEBUG': settings.DEBUG, 'reason': reason, 'no_referer': reason == REASON_NO_REFERER }) return HttpResponseForbidden(t.render(c), content_type='text/html')
def test_docutils(self): t = Template("{% load markup %}{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() # 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: # 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>""")
def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" if request.method == "POST": root = parseString(request.body) first_book = root.firstChild.firstChild title, author = [n.firstChild.nodeValue for n in first_book.childNodes] t = Template("{{ title }} - {{ author }}", name="Book template") c = Context({"title": title, "author": author}) else: t = Template("GET request.", name="Book GET template") c = Context() return HttpResponse(t.render(c))
def test_percent_symbol_escaping(self): from djangocg.template import Template, Context os.chdir(test_dir) call_command("compilemessages", locale=self.LOCALE, stderr=StringIO()) with translation.override(self.LOCALE): t = Template( '{% load i18n %}{% trans "Looks like a str fmt spec %% o but shouldn\'t be interpreted as such" %}' ) rendered = t.render(Context({})) self.assertEqual(rendered, "IT translation contains %% for the above string") t = Template('{% load i18n %}{% trans "Completed 50%% of all the tasks" %}') rendered = t.render(Context({})) self.assertEqual(rendered, "IT translation of Completed 50%% of all the tasks")
def form_view(request): "A view that tests a simple form" if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): t = Template("Valid POST data.", name="Valid POST Template") c = Context() else: t = Template("Invalid POST data. {{ form.errors }}", name="Invalid POST Template") c = Context({"form": form}) else: form = TestForm(request.GET) t = Template("Viewing base form. {{ form }}.", name="Form GET Template") c = Context({"form": form}) return HttpResponse(t.render(c))
def post_view(request): """A view that expects a POST, and returns a different template depending on whether any POST data is available """ if request.method == "POST": if request.POST: t = Template("Data received: {{ data }} is the value.", name="POST Template") c = Context({"data": request.POST["value"]}) else: t = Template("Viewing POST page.", name="Empty POST Template") c = Context() else: t = Template("Viewing GET page.", name="Empty GET Template") c = Context() return HttpResponse(t.render(c))
def directory_index(path, fullpath): try: t = loader.select_template(['static/directory_index.html', 'static/directory_index']) except TemplateDoesNotExist: t = Template(DEFAULT_DIRECTORY_INDEX_TEMPLATE, name='Default directory index template') files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory' : path + '/', 'file_list' : files, }) return HttpResponse(t.render(c))
def test_result_list_empty_changelist_value(self): """ Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields """ new_child = Child.objects.create(name='name', parent=None) request = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) cl = ChangeList(request, Child, list_display, list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) row_html = '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % new_child.id self.assertFalse(table_output.find(row_html) == -1, 'Failed to find expected row element: %s' % table_output)
def test_result_list_html(self): """ Verifies that inclusion tag result_list generates a table when with default ModelAdmin settings. """ new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) cl = ChangeList(request, Child, list_display, list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) row_html = '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' % new_child.id self.assertFalse(table_output.find(row_html) == -1, 'Failed to find expected row element: %s' % table_output)
def test_template(self): # Templates can be created from unicode strings. t1 = Template('ŠĐĆŽćžšđ {{ var }}') # Templates can also be created from bytestrings. These are assumed to # be encoded using UTF-8. s = b'\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91 {{ var }}' t2 = Template(s) s = b'\x80\xc5\xc0' self.assertRaises(TemplateEncodingError, Template, s) # Contexts can be constructed from unicode or UTF-8 bytestrings. c1 = Context({b"var": b"foo"}) c2 = Context({"var": b"foo"}) c3 = Context({b"var": "Đđ"}) c4 = Context({"var": b"\xc4\x90\xc4\x91"}) # Since both templates and all four contexts represent the same thing, # they all render the same (and are returned as unicode objects and # "safe" objects as well, for auto-escaping purposes). self.assertEqual(t1.render(c3), t2.render(c3)) self.assertIsInstance(t1.render(c3), six.text_type) self.assertIsInstance(t1.render(c3), SafeData)
def token_view(request): """A view that uses {% csrf_token %}""" context = RequestContext(request, processors=[csrf]) template = Template("{% csrf_token %}") return HttpResponse(template.render(context))
def show(request): t = Template(TEMPLATE) return HttpResponse(t.render(RequestContext(request)))
def test_markdown_attribute_enable(self): t = Template("{% load markup %}{{ markdown_content|markdown }}") markdown_content = "{@onclick=alert('hi')}some paragraph" rendered = t.render(Context({'markdown_content':markdown_content})).strip() self.assertFalse('@' in rendered)
def test_markdown(self): t = Template("{% load markup %}{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() pattern = re.compile("""<p>Paragraph 1\s*</p>\s*<h2>\s*An h2</h2>""") self.assertTrue(pattern.match(rendered))
def test_no_markdown(self): t = Template("{% load markup %}{{ markdown_content|markdown }}") rendered = t.render(Context({'markdown_content':self.markdown_content})).strip() self.assertEqual(rendered, self.markdown_content)
def test_no_docutils(self): t = Template("{% load markup %}{{ rest_content|restructuredtext }}") rendered = t.render(Context({'rest_content':self.rest_content})).strip() self.assertEqual(rendered, self.rest_content)
def get_view(request): "A simple view that expects a GET request, and returns a rendered template" t = Template("This is a test. {{ var }} is the value.", name="GET Template") c = Context({"var": request.GET.get("var", 42)}) return HttpResponse(t.render(c))
def login_protected_view_changed_redirect(request): "A simple view that is login protected with a custom redirect field set" t = Template("This is a login protected test. Username is {{ user.username }}.", name="Login Template") c = Context({"user": request.user}) return HttpResponse(t.render(c))
def login_protected_view(request): "A simple view that is login protected." t = Template("This is a login protected test. Username is {{ user.username }}.", name="Login Template") c = Context({"user": request.user}) return HttpResponse(t.render(c))