Python django.template.loader.get_template() Examples

The following are 30 code examples for showing how to use django.template.loader.get_template(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.template.loader , or try the search function .

Example 1
Project: OpenMDM   Author: OpenMDM   File: bootstrap.py    License: Apache License 2.0 8 votes vote down vote up
def render(element, markup_classes):
    element_type = element.__class__.__name__.lower()

    if element_type == 'boundfield':
        add_input_classes(element)
        template = get_template("bootstrapform/field.html")
        context = Context({'field': element, 'classes': markup_classes, 'form': element.form})
    else:
        has_management = getattr(element, 'management_form', None)
        if has_management:
            for form in element.forms:
                for field in form.visible_fields():
                    add_input_classes(field)

            template = get_template("bootstrapform/formset.html")
            context = Context({'formset': element, 'classes': markup_classes})
        else:
            for field in element.visible_fields():
                add_input_classes(field)

            template = get_template("bootstrapform/form.html")
            context = Context({'form': element, 'classes': markup_classes})

    return template.render(context) 
Example 2
Project: django-hijack-admin   Author: arteria   File: admin.py    License: MIT License 6 votes vote down vote up
def hijack_field(self, obj):
        hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES

        if 'user_id' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
        elif 'email' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
        else:
            hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))

        button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
        button_context = {
            'hijack_url': hijack_url,
            'username': str(obj),
        }

        return button_template.render(button_context) 
Example 3
Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 6 votes vote down vote up
def send_email_ticket_confirm(request, payment_info):
    """
    :param request Django request object
    :param payment_info Registration object
    """
    mail_title = u"PyCon Korea 2015 등록확인 안내(Registration confirmation)"
    product = Product()
    variables = Context({
        'request': request,
        'payment_info': payment_info,
        'amount': product.price
    })
    html = get_template('mail/ticket_registered_html.html').render(variables)
    text = get_template('mail/ticket_registered_text.html').render(variables)
    
    msg = EmailMultiAlternatives(
        mail_title,
        text,
        settings.EMAIL_SENDER,
        [payment_info.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example 4
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 6 votes vote down vote up
def render(self, context):
        request = context["request"]
        post = getattr(request, "POST", None)
        form = template.Variable(self.value).resolve(context)
        t = get_template("forms/includes/built_form.html")
        context["form"] = form
        form_args = (form, context, post or None)
        form_for_form = FormForForm(*form_args)

        # kind of a hack
        # add the 'data-verify' attribute if the field is marked
        # as a verifiable field
        for i, field in enumerate(form_for_form.form_fields):
            if field.verify:
                form_for_form.fields[field.slug].widget.attrs['data-verify'] = True

            # We give to all the form fields a common class so we can reference 
            # them in the frontend
            fieldAttrs = form_for_form.fields[field.slug].widget.attrs
            fieldAttrs['class'] = fieldAttrs['class']  + ' form-field'

        context["form_for_form"] = form_for_form
        return t.render(context) 
Example 5
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_user(self, text_template, html_template, context):
        offering = context['offering']
        headers = {
                'Precedence': 'bulk',
                'Auto-Submitted': 'auto-generated',
                'X-coursys-topic': 'discussion',
                'X-course': offering.slug,
                'Sender': settings.DEFAULT_SENDER_EMAIL,
                }
        to_email = context['to'].email()
        if offering.taemail():
            from_email = "%s <%s>" % (offering.name(), offering.taemail())
        else:
            from_email = settings.DEFAULT_SENDER_EMAIL
        text_content = get_template(text_template).render(context)
        html_content = get_template(html_template).render(context)
        
        msg = EmailMultiAlternatives(context['subject'], text_content, from_email, [to_email], headers=headers)
        msg.attach_alternative(html_content, "text/html")
        msg.send() 
Example 6
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_notify_completed(self, request, admin, email_cc=None):
        plaintext = get_template('onlineforms/emails/notify_completed.txt')
        html = get_template('onlineforms/emails/notify_completed.html')

        email_context = {'formsub': self, 'admin': admin}
        subject = '%s for %s submission complete' % (self.form.title, self.initiator.name())
        from_email = FormFiller.form_full_email(admin)
        to = self.initiator.full_email()
        if email_cc:
            email_cc = [l.strip() for l in email_cc.split(',')]

        msg = EmailMultiAlternatives(subject=subject, body=plaintext.render(email_context),
                from_email=from_email, to=[to], bcc=[admin.full_email()], cc=email_cc,
                headers={'X-coursys-topic': 'onlineforms'})
        msg.attach_alternative(html.render(email_context), "text/html")
        msg.send()

        FormLogEntry.create(form_submission=self, category='MAIL',
                    description='Notified %s that form submission was completed by %s.'
                                % (to, from_email)) 
Example 7
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def email_notify_new_owner(self, request, admin):
        plaintext = get_template('onlineforms/emails/notify_new_owner.txt')
        html = get_template('onlineforms/emails/notify_new_owner.html')

        full_url = request.build_absolute_uri(reverse('onlineforms:view_submission',
                                    kwargs={'form_slug': self.form.slug,
                                            'formsubmit_slug': self.slug}))
        email_context = {'formsub': self, 'admin': admin, 'adminurl': full_url}
        subject = '%s submission transferred' % (self.form.title)
        from_email = FormFiller.form_full_email(admin)
        to = self.owner.notify_emails()
        msg = EmailMultiAlternatives(subject=subject, body=plaintext.render(email_context),
                from_email=from_email, to=to, bcc=[admin.full_email()],
                headers={'X-coursys-topic': 'onlineforms'})
        msg.attach_alternative(html.render(email_context), "text/html")
        msg.send()

        FormLogEntry.create(form_submission=self, category='MAIL',
                    description='Notified group "%s" that form submission was transferred to them.'
                                % (self.owner.name,)) 
Example 8
Project: browserscope   Author: elsigh   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def GetStatsDataTemplatized(params, template='table'):
    """Returns the stats table run through a template.

    Args:
        params: Example:
                        params = {
                            'v': one of the keys in user_agent.BROWSER_NAV,
                            'current_user_agent': a user agent entity,
                            'user_agents': list_of user agents,
                            'tests': list of test names,
                            'stats': dict - stats[test_name][user_agent],
                            'total_runs': total_runs[test_name],
                            'request_path': request.path,
                            'params': result_parent.params, #optional
                        }

    """
    params['browser_nav'] = result_stats.BROWSER_NAV
    params['is_admin'] = users.is_current_user_admin()
    if not re.search('\?', params['request_path']):
        params['request_path'] = params['request_path'] + '?'
    t = loader.get_template('stats_%s.html' % template)
    template_rendered = t.render(Context(params))
    return template_rendered 
Example 9
Project: wagtailinvoices   Author: SableWalnut   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def serve_pdf(self, request):
        # Render html content through html template with context
        template = get_template(settings.PDF_TEMPLATE)
        context = {
            'invoice': self,
        }

        html = template.render(context)

        # Write PDF to file
        document_html = HTML(string=html, base_url=request.build_absolute_uri())
        document = document_html.render()
        if len(document.pages) > 1:
            for page in document.pages[1:]:
                str(page)
            pdf = document.write_pdf()
        else:
            pdf = document.write_pdf()
        #response = HttpResponse(html)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'filename="Invoice {0} | Invoice {0}.pdf"'.format(self.id)
        return response 
Example 10
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'
    return http.HttpResponseNotFound(body, content_type=content_type) 
Example 11
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bad_request(request, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 12
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example 13
def search(request):
    query = request.GET['q']
    t = loader.get_template('result.html')
    results = Entry.objects.filter(Q(title__icontains=query) | Q(body__icontains=query))#.order_by('created')
    paginator = Paginator(results, 2) #show 10 articles per page
    page = request.GET.get('page')
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        results = paginator.page(1)
    except EmptyPage:
        results = paginator.page(paginator.num_pages)

    c = Context({ 'query': query, 'results':results })
    return HttpResponse(t.render(c))

#result.html 
Example 14
Project: breadbot   Author: ideamark   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        str_xml = ET.fromstring(request.body)
        from_user = str_xml.find('FromUserName').text
        to_user = str_xml.find('ToUserName').text
        cur_time = str(int(time.time()))
        msg_type = str_xml.find('MsgType').text
        content = '...'
        if msg_type == 'text':
            content = str_xml.find('Content').text
            if '[Unsupported Message]' in content:
                res = 'Error: unknow message'
            else:
                res = core.chat.Chat(db).response(from_user, content)
        else:
            res = "Sorry, I can't chat by %s" % msg_type
        template = loader.get_template('wechat/text_message_template.xml')
        context = {'toUser': from_user,
                   'fromUser': to_user,
                   'currentTtime': cur_time,
                   'content': res}
        context_xml = template.render(context)
        log_str = '\nUser:   %s\nAsk:    %s\nAnswer: %s\n' % \
                  (from_user, content, res)
        core.common.ChatLog().write(log_str)
        return HttpResponse(context_xml) 
Example 15
Project: kobo-predict   Author: awemulya   File: filters.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def do_loadmacros(parser, token):
    try:
        tag_name, filename = token.split_contents()
    except IndexError:
        m = ("'%s' tag requires at least one argument (macro name)"
             % token.contents.split()[0])
        raise template.TemplateSyntaxError(m)
    if filename[0] in ('"', "'") and filename[-1] == filename[0]:
        filename = filename[1:-1]
    t = get_template(filename)
    macros = t.nodelist.get_nodes_by_type(DefineMacroNode)
    ## Metadata of each macro are stored in a new attribute
    ## of 'parser' class. That way we can access it later
    ## in the template when processing 'usemacro' tags.
    _setup_macros_dict(parser)
    for macro in macros:
        parser._macros[macro.name] = macro
    return LoadMacrosNode() 
Example 16
Project: django-sitemessage   Author: idlesign   File: sitemessage.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, context):
        resolve = lambda arg: arg.resolve(context) if isinstance(arg, FilterExpression) else arg

        prefs_obj = resolve(self.prefs_obj)
        if not isinstance(prefs_obj, tuple):
            if settings.DEBUG:
                raise SiteMessageConfigurationError(
                    '`sitemessage_prefs_table` template tag expects a tuple generated '
                    'by `get_user_preferences_for_ui` but `%s` is given.' % type(prefs_obj))
            return ''  # Silent fall.

        context.push()
        context['sitemessage_user_prefs'] = prefs_obj
        contents = get_template(
            resolve(self.use_template or 'sitemessage/user_prefs_table.html')
        ).render(context.flatten() if _CONTEXT_FLATTEN else context)
        context.pop()

        return contents 
Example 17
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    :template: :file:`500.html`
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseServerError(
            "<h1>Server Error (500)</h1>", content_type="text/html"
        )
    return http.HttpResponseServerError(template.render(request=request))


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 18
Project: telemetry-analysis-service   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    :template: :file:`403.html`

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseForbidden(
            "<h1>403 Forbidden</h1>", content_type="text/html"
        )
    return http.HttpResponseForbidden(
        template.render(request=request, context={"exception": force_text(exception)})
    ) 
Example 19
Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 6 votes vote down vote up
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 20
Project: bioforum   Author: reBiocoder   File: defaults.py    License: MIT License 6 votes vote down vote up
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return HttpResponseForbidden(
        template.render(request=request, context={'exception': str(exception)})
    ) 
Example 21
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def render_flatpage(request, f):
    """
    Internal interface to the flat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated:
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        template = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        template = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in flatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    response = HttpResponse(template.render({'flatpage': f}, request))
    return response 
Example 22
Project: waliki   Author: mgaitan   File: bootstrap_tags.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_bootstrap_inline(form):
    template = get_template("bootstrap/form.html")
    form = _preprocess_fields(form)

    for field in form.fields:
        name = form.fields[field].widget.__class__.__name__.lower()
        if not name.startswith("radio") and not name.startswith("checkbox"):
            form.fields[field].widget.attrs["placeholder"] = form.fields[field].label
    css_classes = {
        "label": "sr-only",
        "single_container": "",
        "wrap": "",
    }
    context = {
        "form": form,
        "css_classes": css_classes,
    }
    return template.render(contex) 
Example 23
Project: pythonjobs.ie   Author: kimeraapp   File: services.py    License: GNU General Public License v2.0 5 votes vote down vote up
def send_confirmation_mail(job):
    subject = "You just posted a job on pythonjobs.ie"
    template = loader.get_template("email.html")
    body = template.render({'job': job})
    to_email = [job.email]
    from_email = "info@kimera.io"

    return send_mail(subject, body, from_email, to_email,
                     fail_silently=True, html_message=body) 
Example 24
Project: TwitterFriends   Author: mgmacias95   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def index(request):
    # netjson = generate_net_json()
    template = loader.get_template('findfriends/index.html')
    context = {
        # 'netjson': netjson,
    }
    return HttpResponse(template.render(context, request)) 
Example 25
Project: pyconkr-2015   Author: pythonkr   File: helper.py    License: MIT License 5 votes vote down vote up
def sendEmailToken(request, token):
    variables = Context({
        'request': request,
        'token': token,
    })
    html = get_template('mail/token_html.html').render(variables)
    text = get_template('mail/token_text.html').render(variables)

    msg = EmailMultiAlternatives(
        settings.EMAIL_LOGIN_TITLE,
        text,
        settings.EMAIL_SENDER,
        [token.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False) 
Example 26
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 5 votes vote down vote up
def render_ranking(context, ranking_definition):
    t = get_template('ranking.html')
    context['ranking'] = ranking_definition

    r = t.render(context)
    return r 
Example 27
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 5 votes vote down vote up
def render_ranking_all(context, ranking_definition, search_term):
    t = get_template('ranking_all.html')
    context['ranking'] = ranking_definition
    context['ranking_calculate_all'] = ranking_definition.calculate_all(search_term = search_term)

    r = t.render(context)
    return r 
Example 28
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 5 votes vote down vote up
def call_to_action(context, document_set):
    t = get_template("call_to_action.html")
    context["document_set"] = document_set

    return t.render(context) 
Example 29
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 5 votes vote down vote up
def documents_verified(context, document_set):
    t = get_template("documents_verified.html")
    context["document_set"] = document_set

    return t.render(context) 
Example 30
Project: crowdata   Author: crowdata   File: crowdataapp_tags.py    License: MIT License 5 votes vote down vote up
def list_ranking_organizations(context, organizations, profile = None):
    t = get_template("list_ranking_organizations.html")
    context["organizations"] = organizations
    return t.render(context)