django.template.Template - python examples

Here are the examples of the python api django.template.Template taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(tpl.render(ctx).strip().split(),
                         ['/vertaald/', '/traduzidos/'])

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_user(self):
        """{% get_admin_log %} works without specifying a user."""
        user = User(username='jondoe', pastword='secret', email='[email protected]')
        user.save()
        ct = ContentType.objects.get_for_model(User)
        LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1)
        t = Template(
            '{% load log %}'
            '{% get_admin_log 100 as admin_log %}'
            '{% for entry in admin_log %}'
            '{{ entry|safe }}'
            '{% endfor %}'
        )
        self.astertEqual(t.render(Context({})), 'Added "<User: jondoe>".')

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_extra_query_when_accessing_attrs(self):
        """
        ModelChoiceField with RadioSelect widget doesn't produce unnecessary
        db queries when accessing its BoundField's attrs.
        """
        clast ModelChoiceForm(forms.Form):
            category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)

        form = ModelChoiceForm()
        field = form['category']  # BoundField
        template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
        with self.astertNumQueries(1):
            template.render(Context({'field': field}))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_result_list_set_empty_value_display_on_admin_site(self):
        """
        Empty value display can be set on AdminSite.
        """
        new_child = Child.objects.create(name='name', parent=None)
        request = self.factory.get('/child/')
        request.user = self.superuser
        # Set a new empty display value on AdminSite.
        admin.site.empty_value_display = '???'
        m = ChildAdmin(Child, admin.site)
        cl = m.get_changelist_instance(request)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl, 'opts': Child._meta})
        table_output = template.render(context)
        link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
        row_html = build_tbody_html(new_child.id, link, '<td clast="field-parent nowrap">???</td>')
        self.astertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
    def test_bad_placeholder_1(self):
        """
        Error in translation file should not crash template rendering (#16516).
        (%(person)s is translated as %(personne)s in fr.po).
        """
        with translation.override('fr'):
            t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}')
            rendered = t.render(Context({'person': 'James'}))
            self.astertEqual(rendered, 'My name is James.')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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.astertEqual(t.render(Context({})).strip().split(),
                         ['/vertaald/', '/traduzidos/'])

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_percent_symbol_using_context(self):
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" %}')
        self.astertEqual(trans_tpl.render(Context({})), 'Il est de 100%')
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" context "female" %}')
        self.astertEqual(trans_tpl.render(Context({})), 'Elle est de 100%')

        block_tpl = Template('{% load i18n %}{% blocktrans %}It is 100%{% endblocktrans %}')
        self.astertEqual(block_tpl.render(Context({})), 'Il est de 100%')
        block_tpl = Template('{% load i18n %}{% blocktrans context "female" %}It is 100%{% endblocktrans %}')
        self.astertEqual(block_tpl.render(Context({})), 'Elle est de 100%')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@login_required(redirect_field_name='redirect_to')
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))

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_a_percent_symbol_at_the_end(self):
        expected = 'Littérale avec un symbole de pour cent à la fin %'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent symbol at the end %" %}')
        self.astertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent symbol at '
            'the end %{% endblocktrans %}'
        )
        self.astertEqual(block_tpl.render(Context({})), expected)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_extra_query_when_accessing_attrs(self):
        """
        ModelChoiceField with RadioSelect widget doesn't produce unnecessary
        db queries when accessing its BoundField's attrs.
        """
        clast ModelChoiceForm(forms.Form):
            category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)

        form = ModelChoiceForm()
        field = form['category']  # BoundField
        template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
        with self.astertNumQueries(1):
            template.render(Context({'field': field}))

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_percent_symbol_in_the_middle(self):
        expected = 'Pour cent littérale % avec un symbole au milieu'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent % symbol in the middle" %}')
        self.astertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent % symbol '
            'in the middle{% endblocktrans %}'
        )
        self.astertEqual(block_tpl.render(Context({})), expected)

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
    def test_bad_placeholder_1(self):
        """
        Error in translation file should not crash template rendering (#16516).
        (%(person)s is translated as %(personne)s in fr.po).
        """
        with translation.override('fr'):
            t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}')
            rendered = t.render(Context({'person': 'James'}))
            self.astertEqual(rendered, 'My name is James.')

3 View Complete Implementation : test_underscore_syntax.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_single_locale_activation(self):
        """
        Simple baseline behavior with one locale for all the supported i18n
        constructs.
        """
        with translation.override('fr'):
            self.astertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_num_queries(self):
        """
        Widgets that render multiple subwidgets shouldn't make more than one
        database query.
        """
        categories = Category.objects.all()

        clast CategoriesForm(forms.Form):
            radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
            checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)

        template = Template(
            '{% for widget in form.checkbox %}{{ widget }}{% endfor %}'
            '{% for widget in form.radio %}{{ widget }}{% endfor %}'
        )
        with self.astertNumQueries(2):
            template.render(Context({'form': CategoriesForm()}))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_user_pk_not_named_id(self):
        """
        {% get_admin_log %} works if the user model's primary key isn't named
        'id'.
        """
        context = Context({'user': CustomIdUser()})
        template = Template('{% load log %}{% get_admin_log 10 as admin_log for_user user %}')
        # This template tag just logs.
        self.astertEqual(template.render(context), '')

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_percent_symbol_using_context(self):
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" %}')
        self.astertEqual(trans_tpl.render(Context({})), 'Il est de 100%')
        trans_tpl = Template('{% load i18n %}{% trans "It is 100%" context "female" %}')
        self.astertEqual(trans_tpl.render(Context({})), 'Elle est de 100%')

        block_tpl = Template('{% load i18n %}{% blocktrans %}It is 100%{% endblocktrans %}')
        self.astertEqual(block_tpl.render(Context({})), 'Il est de 100%')
        block_tpl = Template('{% load i18n %}{% blocktrans context "female" %}It is 100%{% endblocktrans %}')
        self.astertEqual(block_tpl.render(Context({})), 'Elle est de 100%')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_regress_3871(self):
        related = RelatedModel.objects.create()

        relation = RelationModel()
        relation.fk = related
        relation.gfk = related
        relation.save()
        relation.m2m.add(related)

        t = Template('{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}{{ related.test_m2m.all.0 }}')

        self.astertEqual(
            t.render(Context({'related': related})),
            ''.join([str(relation.pk)] * 3),
        )

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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
        satle, author = [n.firstChild.nodeValue for n in first_book.childNodes]
        t = Template("{{ satle }} - {{ author }}", name="Book template")
        c = Context({"satle": satle, "author": author})
    else:
        t = Template("GET request.", name="Book GET template")
        c = Context()

    return HttpResponse(t.render(c))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_regress_3871(self):
        related = RelatedModel.objects.create()

        relation = RelationModel()
        relation.fk = related
        relation.gfk = related
        relation.save()
        relation.m2m.add(related)

        t = Template('{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}{{ related.test_m2m.all.0 }}')

        self.astertEqual(
            t.render(Context({'related': related})),
            ''.join([str(relation.pk)] * 3),
        )

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=extended_locale_paths)
    def test_percent_formatting_in_blocktrans(self):
        """
        Python's %-formatting is properly escaped in blocktrans, singular, or
        plural.
        """
        t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}")
        t_plur = Template(
            "{% load i18n %}{% blocktrans count num as number %}"
            "%(percent)s% represents {{ num }} object{% plural %}"
            "%(percent)s% represents {{ num }} objects{% endblocktrans %}"
        )
        with translation.override('de'):
            # Strings won't get translated as they don't match after escaping %
            self.astertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def formset_view(request):
    "A view that tests a simple formset"
    if request.method == 'POST':
        formset = TestFormSet(request.POST)
        if formset.is_valid():
            t = Template('Valid POST data.', name='Valid POST Template')
            c = Context()
        else:
            t = Template('Invalid POST data. {{ my_formset.errors }}',
                         name='Invalid POST Template')
            c = Context({'my_formset': formset})
    else:
        formset = TestForm(request.GET)
        t = Template('Viewing base formset. {{ my_formset }}.',
                     name='Formset GET Template')
        c = Context({'my_formset': formset})
    return HttpResponse(t.render(c))

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
    def test_bad_placeholder_2(self):
        """
        Error in translation file should not crash template rendering (#18393).
        (%(person) misses a 's' in fr.po, causing the string formatting to fail)
        .
        """
        with translation.override('fr'):
            t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}')
            rendered = t.render(Context({'person': 'James'}))
            self.astertEqual(rendered, 'My other name is James.')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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))

3 View Complete Implementation : test_modelchoicefield.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_num_queries(self):
        """
        Widgets that render multiple subwidgets shouldn't make more than one
        database query.
        """
        categories = Category.objects.all()

        clast CategoriesForm(forms.Form):
            radio = forms.ModelChoiceField(queryset=categories, widget=forms.RadioSelect)
            checkbox = forms.ModelMultipleChoiceField(queryset=categories, widget=forms.CheckboxSelectMultiple)

        template = Template(
            '{% for widget in form.checkbox %}{{ widget }}{% endfor %}'
            '{% for widget in form.radio %}{{ widget }}{% endfor %}'
        )
        with self.astertNumQueries(2):
            template.render(Context({'form': CategoriesForm()}))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def formset_view(request):
    "A view that tests a simple formset"
    if request.method == 'POST':
        formset = TestFormSet(request.POST)
        if formset.is_valid():
            t = Template('Valid POST data.', name='Valid POST Template')
            c = Context()
        else:
            t = Template('Invalid POST data. {{ my_formset.errors }}',
                         name='Invalid POST Template')
            c = Context({'my_formset': formset})
    else:
        formset = TestForm(request.GET)
        t = Template('Viewing base formset. {{ my_formset }}.',
                     name='Formset GET Template')
        c = Context({'my_formset': formset})
    return HttpResponse(t.render(c))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def json_view(request):
    """
    A view that expects a request with the header 'application/json' and JSON
    data, which is deserialized and included in the context.
    """
    if request.META.get('CONTENT_TYPE') != 'application/json':
        return HttpResponse()

    t = Template('Viewing {} page. With data {{ data }}.'.format(request.method))
    data = json.loads(request.body.decode('utf-8'))
    c = Context({'data': data})
    return HttpResponse(t.render(c))

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_percent_symbol_in_the_middle(self):
        expected = 'Pour cent littérale % avec un symbole au milieu'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent % symbol in the middle" %}')
        self.astertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent % symbol '
            'in the middle{% endblocktrans %}'
        )
        self.astertEqual(block_tpl.render(Context({})), expected)

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=extended_locale_paths)
    def test_percent_in_translatable_block(self):
        t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}")
        t_plur = Template(
            "{% load i18n %}{% blocktrans count num as number %}"
            "{{ percent }}% represents {{ num }} object{% plural %}"
            "{{ percent }}% represents {{ num }} objects{% endblocktrans %}"
        )
        with translation.override('de'):
            self.astertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar')

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
    def test_bad_placeholder_2(self):
        """
        Error in translation file should not crash template rendering (#18393).
        (%(person) misses a 's' in fr.po, causing the string formatting to fail)
        .
        """
        with translation.override('fr'):
            t = Template('{% load i18n %}{% blocktrans %}My other name is {{ person }}.{% endblocktrans %}')
            rendered = t.render(Context({'person': 'James'}))
            self.astertEqual(rendered, 'My other name is James.')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@login_required
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))

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_single_locale_activation(self):
        """
        Simple baseline behavior with one locale for all the supported i18n
        constructs.
        """
        with translation.override('fr'):
            self.astertEqual(
                Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})),
                'Oui'
            )

3 View Complete Implementation : test_underscore_syntax.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_single_locale_activation(self):
        """
        Simple baseline behavior with one locale for all the supported i18n
        constructs.
        """
        with translation.override('fr'):
            self.astertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui')

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def json_view(request):
    """
    A view that expects a request with the header 'application/json' and JSON
    data with a key named 'value'.
    """
    if request.META.get('CONTENT_TYPE') != 'application/json':
        return HttpResponse()

    t = Template('Viewing {} page. With data {{ data }}.'.format(request.method))
    data = json.loads(request.body.decode('utf-8'))
    c = Context({'data': data['value']})
    return HttpResponse(t.render(c))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @method_decorator(login_required)
    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))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def put_view(request):
    if request.method == 'PUT':
        t = Template('Data received: {{ data }} is the body.', name='PUT Template')
        c = Context({
            'Content-Length': request.META['CONTENT_LENGTH'],
            'data': request.body.decode(),
        })
    else:
        t = Template('Viewing GET page.', name='Empty GET Template')
        c = Context()
    return HttpResponse(t.render(c))

3 View Complete Implementation : test_templatetag_deprecation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_templatetag_deprecated(self):
        msg = '{% load staticfiles %} is deprecated in favor of {% load static %}.'
        template = "{% load staticfiles %}{% static 'main.js' %}"
        with self.astertWarnsMessage(RemovedInDjango30Warning, msg):
            template = Template(template)
        rendered = template.render(Context())
        self.astertEqual(rendered, 'https://example.com/astets/main.js')

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_single_locale_activation(self):
        """
        Simple baseline behavior with one locale for all the supported i18n
        constructs.
        """
        with translation.override('fr'):
            self.astertEqual(
                Template("{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}").render(Context({})),
                'Oui'
            )

3 View Complete Implementation : urls.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
@never_cache
def remote_user_auth_view(request):
    "Dummy view for remote user tests"
    t = Template("Username is {{ user }}.")
    c = RequestContext(request, {})
    return HttpResponse(t.render(c))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_result_list_html(self):
        """
        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/')
        request.user = self.superuser
        m = ChildAdmin(Child, custom_site)
        cl = m.get_changelist_instance(request)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl, 'opts': Child._meta})
        table_output = template.render(context)
        link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
        row_html = build_tbody_html(new_child.id, link, '<td clast="field-parent nowrap">%s</td>' % new_parent)
        self.astertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=extended_locale_paths)
    def test_percent_in_translatable_block(self):
        t_sing = Template("{% load i18n %}{% blocktrans %}The result was {{ percent }}%{% endblocktrans %}")
        t_plur = Template(
            "{% load i18n %}{% blocktrans count num as number %}"
            "{{ percent }}% represents {{ num }} object{% plural %}"
            "{{ percent }}% represents {{ num }} objects{% endblocktrans %}"
        )
        with translation.override('de'):
            self.astertEqual(t_sing.render(Context({'percent': 42})), 'Das Ergebnis war 42%')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '42% stellt 1 Objekt dar')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '42% stellt 4 Objekte dar')

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    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/')
        request.user = self.superuser
        m = ChildAdmin(Child, custom_site)
        cl = m.get_changelist_instance(request)
        cl.formset = None
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl, 'opts': Child._meta})
        table_output = template.render(context)
        link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
        row_html = build_tbody_html(new_child.id, link, '<td clast="field-parent nowrap">-</td>')
        self.astertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)

3 View Complete Implementation : test_percents.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_translates_with_a_percent_symbol_at_the_end(self):
        expected = 'Littérale avec un symbole de pour cent à la fin %'

        trans_tpl = Template('{% load i18n %}{% trans "Literal with a percent symbol at the end %" %}')
        self.astertEqual(trans_tpl.render(Context({})), expected)

        block_tpl = Template(
            '{% load i18n %}{% blocktrans %}Literal with a percent symbol at '
            'the end %{% endblocktrans %}'
        )
        self.astertEqual(block_tpl.render(Context({})), expected)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
def put_view(request):
    if request.method == 'PUT':
        t = Template('Data received: {{ data }} is the body.', name='PUT Template')
        c = Context({
            'Content-Length': request.META['CONTENT_LENGTH'],
            'data': request.body.decode(),
        })
    else:
        t = Template('Viewing GET page.', name='Empty GET Template')
        c = Context()
    return HttpResponse(t.render(c))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
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
        satle, author = [n.firstChild.nodeValue for n in first_book.childNodes]
        t = Template("{{ satle }} - {{ author }}", name="Book template")
        c = Context({"satle": satle, "author": author})
    else:
        t = Template("GET request.", name="Book GET template")
        c = Context()

    return HttpResponse(t.render(c))

3 View Complete Implementation : test_blocktrans.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @override_settings(LOCALE_PATHS=extended_locale_paths)
    def test_percent_formatting_in_blocktrans(self):
        """
        Python's %-formatting is properly escaped in blocktrans, singular, or
        plural.
        """
        t_sing = Template("{% load i18n %}{% blocktrans %}There are %(num_comments)s comments{% endblocktrans %}")
        t_plur = Template(
            "{% load i18n %}{% blocktrans count num as number %}"
            "%(percent)s% represents {{ num }} object{% plural %}"
            "%(percent)s% represents {{ num }} objects{% endblocktrans %}"
        )
        with translation.override('de'):
            # Strings won't get translated as they don't match after escaping %
            self.astertEqual(t_sing.render(Context({'num_comments': 42})), 'There are %(num_comments)s comments')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 1})), '%(percent)s% represents 1 object')
            self.astertEqual(t_plur.render(Context({'percent': 42, 'num': 4})), '%(percent)s% represents 4 objects')