Python django.template.loader.render_to_string() Examples

The following are 30 code examples of django.template.loader.render_to_string(). 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 also want to check out all available functions/classes of the module django.template.loader , or try the search function .
Example #1
Source File: puput_tags.py    From puput with MIT License 7 votes vote down vote up
def show_comments(context):
    blog_page = context['blog_page']
    entry = context['self']
    if blog_page.display_comments:
        try:
            comment_class = import_model(settings.PUPUT_COMMENTS_PROVIDER)(blog_page, entry)
            comment_context = comment_class.get_context()
            comment_context.update(context.flatten())
            return render_to_string(comment_class.template, context=comment_context)
        except AttributeError:
            raise Exception('To use comments you need to specify '
                            'PUPUT_COMMENTS_PROVIDER in settings.')
    return ""


# Avoid to import endless_pagination in installed_apps and in the templates 
Example #2
Source File: views.py    From gazetteer with MIT License 7 votes vote down vote up
def backbone(request):
    instance_name = instance_settings.SHORT_NAME
    instance_templates_base = join('instance_templates', instance_name)
    footer_template = join(instance_templates_base, 'footer.html')
    try:
        footer_content = render_to_string(footer_template)
    except:
        footer_content = ''
    context = {
        'site_title': instance_settings.SITE_TITLE,
        'app_base': instance_settings.APP_BASE,
        'footer': footer_content,
        'debug': settings.DEBUG
    }
    return render(request, "backbone.html", context)

#FIXME: move to models 
Example #3
Source File: password_reset_serializer.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_password_reset_email(user, reset_url,
                             subject_template_name='registration/password_reset_subject.txt',  # noqa
                             email_template_name='api_password_reset_email.html',  # noqa
                             token_generator=default_token_generator):
    """Creates the subject and email body for password reset email."""
    result = urlparse(reset_url)
    site_name = domain = result.hostname
    c = {
        'email': user.email,
        'domain': domain,
        'path': result.path,
        'site_name': site_name,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'username': user.username,
        'encoded_username': urlsafe_base64_encode(user.username),
        'token': token_generator.make_token(user),
        'protocol': result.scheme if result.scheme != '' else 'http',
    }
    subject = loader.render_to_string(subject_template_name, c)
    # Email subject *must not* contain newlines
    subject = ''.join(subject.splitlines())
    email = loader.render_to_string(email_template_name, c)

    return subject, email 
Example #4
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def form_valid(self, form):
        user = self.request.user
        new_email = form.cleaned_data['email']

        # URLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(new_email),
            'user': user,
        }

        subject = render_to_string('register/mail_template/email_change/subject.txt', context)
        message = render_to_string('register/mail_template/email_change/message.txt', context)
        send_mail(subject, message, None, [new_email])

        return redirect('register:email_change_done') 
Example #5
Source File: views.py    From django-register-sample with MIT License 6 votes vote down vote up
def form_valid(self, form):
        """仮登録と本登録用メールの発行."""
        # 仮登録と本登録の切り替えは、is_active属性を使うと簡単です。
        # 退会処理も、is_activeをFalseにするだけにしておくと捗ります。
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        # アクティベーションURLの送付
        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(user.pk),
            'user': user,
        }

        subject = render_to_string('register/mail_template/create/subject.txt', context)
        message = render_to_string('register/mail_template/create/message.txt', context)

        user.email_user(subject, message)
        return redirect('register:user_create_done') 
Example #6
Source File: topnav.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def block_top_navbar(self, context, nodes):
        search_models = []

        site_name = self.admin_site.name
        if self.global_search_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_search_models

        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "view"):
                info = (app_label, model._meta.model_name)
                if getattr(self.admin_site._registry[model], 'search_fields', None):
                    try:
                        search_models.append({
                            'title': _('Search %s') % capfirst(model._meta.verbose_name_plural),
                            'url': reverse('xadmin:%s_%s_changelist' % info, current_app=site_name),
                            'model': model
                        })
                    except NoReverseMatch:
                        pass
        return nodes.append(loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'search_models': search_models, 'search_name': SEARCH_VAR})) 
Example #7
Source File: detail.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
        super(ShowField, self).render(form, form_style, context, template_pack, extra_context, **kwargs)
        if extra_context is None:
            extra_context = {}
        if hasattr(self, 'wrapper_class'):
            extra_context['wrapper_class'] = self.wrapper_class

        if self.attrs:
            if 'detail-class' in self.attrs:
                extra_context['input_class'] = self.attrs['detail-class']
            elif 'class' in self.attrs:
                extra_context['input_class'] = self.attrs['class']

        html = ''
        for field, result in self.results:
            extra_context['result'] = result
            if field in form.fields:
                if form.fields[field].widget != forms.HiddenInput:
                    extra_context['field'] = form[field]
                    html += loader.render_to_string(self.template, extra_context)
            else:
                extra_context['field'] = field
                html += loader.render_to_string(self.template, extra_context)
        return html 
Example #8
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def render(self):
        """
        Generates the JavaScript necessary for displaying this Google Map.
        """
        params = {'calc_zoom': self.calc_zoom,
                  'center': self.center,
                  'dom_id': self.dom_id,
                  'js_module': self.js_module,
                  'kml_urls': self.kml_urls,
                  'zoom': self.zoom,
                  'polygons': self.polygons,
                  'polylines': self.polylines,
                  'icons': self.icons,
                  'markers': self.markers,
                  }
        params.update(self.extra_context)
        return render_to_string(self.template, params) 
Example #9
Source File: topnav.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def block_top_navmenu(self, context, nodes):
        add_models = []

        site_name = self.admin_site.name

        if self.global_add_models == None:
            models = self.admin_site._registry.keys()
        else:
            models = self.global_add_models
        for model in models:
            app_label = model._meta.app_label

            if self.has_model_perm(model, "add"):
                info = (app_label, model._meta.model_name)
                try:
                    add_models.append({
                        'title': _('Add %s') % capfirst(model._meta.verbose_name),
                        'url': reverse('xadmin:%s_%s_add' % info, current_app=site_name),
                        'model': model
                    })
                except NoReverseMatch:
                    pass

        nodes.append(
            loader.render_to_string('xadmin/blocks/comm.top.topnav.html', {'add_models': add_models})) 
Example #10
Source File: views.py    From FIR with GNU General Public License v3.0 6 votes vote down vote up
def edit_subscription(request, object_id=None):
    instance = None
    if object_id is not None:
        instance = get_object_or_404(NotificationPreference, pk=object_id, user=request.user)
    if request.method == 'POST':
        form = NotificationPreferenceForm(instance=instance, data=request.POST, user=request.user)
        if form.is_valid():
            form.save()
            return JsonResponse({'status': 'success'})
        else:
            errors = render_to_string("fir_notifications/subscribe.html",
                                      {'form': form})
            return JsonResponse({'status': 'error', 'data': errors})
    else:
        form = NotificationPreferenceForm(instance=instance, user=request.user)
    return render(request, "fir_notifications/subscribe.html", {'form': form}) 
Example #11
Source File: mobile_survey.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_mobile_survey_start(self, request, mobile_survey):
        admin_email = settings.ADMINS[0][1] if settings.ADMINS else ""
        email_context = {
            "button_text": _("Logon to {app_name}".format(app_name=settings.APP_NAME)),
            "link": request.build_absolute_uri(reverse("home")),
            "greeting": _(
                "Welcome to Arches!  You've just been added to a Mobile Survey.  \
                Please take a moment to review the mobile_survey description and mobile_survey start and end dates."
            ),
            "closing": _(f"If you have any qustions contact the site administrator at {admin_email}."),
        }

        html_content = render_to_string("email/general_notification.htm", email_context)
        text_content = strip_tags(html_content)  # this strips the html, so people will have the text as well.

        # create the email, and attach the HTML version as well.
        for user in self.get_mobile_survey_users(mobile_survey):
            msg = EmailMultiAlternatives(
                _("You've been invited to an {app_name} Survey!".format(app_name=settings.APP_NAME)),
                text_content,
                admin_email,
                [user.email],
            )
            msg.attach_alternative(html_content, "text/html")
            msg.send() 
Example #12
Source File: base.py    From django-herald with MIT License 6 votes vote down vote up
def render(self, render_type, context):
        """
        Renders the template

        :param render_type: the content type to render
        :param context: context data dictionary
        :return: the rendered content
        """

        assert render_type in self.render_types, 'Invalid Render Type'

        try:
            content = render_to_string('herald/{}/{}.{}'.format(
                render_type,
                self.template_name,
                'txt' if render_type == 'text' else render_type
            ), context)
        except TemplateDoesNotExist:
            content = None

            if settings.DEBUG:
                raise

        return content 
Example #13
Source File: forms.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Sends a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send() 
Example #14
Source File: models.py    From anytask with MIT License 6 votes vote down vote up
def send_activation_email(self, site=None):
        if not site:
            site = Site.objects.get_current()

        subject = render_to_string('email_activate_subject.txt')
        subject = ''.join(subject.splitlines())

        context = {
            'user': self.user,
            'user_info': json.loads(self.user_info),
            'domain': str(site),
            'activation_key': self.activation_key,
            'is_updating': self.is_updating
        }

        plain_text = render_to_string('email_activate.txt', context)
        html = render_to_string('email_activate.html', context)

        send_mass_mail_html([(subject, plain_text, html, settings.DEFAULT_FROM_EMAIL, [self.user.email])]) 
Example #15
Source File: digest.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def create_digest_email(user, digest_frequency, as_of):
    """Return the digest email message for user based on when they last received a digest message."""
    start = user_digest_start(user, digest_frequency, as_of)
    context = notification_digest(user, start, as_of)

    logger.debug('Digest as of %s: %s', start, context)

    if context:
        context['timestamp'] = as_of
        context['site'] = Site.objects.get_current()
        context['digest_frequency'] = digest_frequency.name

        subject = render_to_string('boards/email/email_digest_subject.txt', context=context)
        # remove superfluous line breaks
        subject = " ".join(subject.splitlines()).strip()

        text_body = render_to_string('boards/email/email_digest_message.txt', context=context)
        html_body = render_to_string('boards/email/email_digest_message.html', context=context)

        email = EmailMultiAlternatives(subject=subject, body=text_body, to=[user.email])
        email.attach_alternative(html_body, "text/html")
        return email
    else:
        return None 
Example #16
Source File: shield_identicon.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def generate_svg(genome):
    treatments = [
        {"function": single_color, "weight": 1},
        {"function": two_color, "weight": 4},
        {"function": stripes, "weight": 6},
    ]
    treatment_context = genome.weighted_choice(treatments)["function"]
    field_color = genome.color()
    pattern_color = genome.pick_pair(field_color)
    context = {
        "emoji": genome.emoji(),
        "field_color": field_color.css_color,
        "pattern_color": pattern_color.css_color,
    }
    context.update(treatment_context(genome))

    return render_to_string("identicon.svg", context) 
Example #17
Source File: shortcuts.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def render_to_response(template_name, context=None,
                       context_instance=_context_instance_undefined,
                       content_type=None, status=None, dirs=_dirs_undefined,
                       dictionary=_dictionary_undefined, using=None):
    """
    Returns a HttpResponse whose content is filled with the result of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    if (context_instance is _context_instance_undefined
            and dirs is _dirs_undefined
            and dictionary is _dictionary_undefined):
        # No deprecated arguments were passed - use the new code path
        content = loader.render_to_string(template_name, context, using=using)

    else:
        # Some deprecated arguments were passed - use the legacy code path
        content = loader.render_to_string(
            template_name, context, context_instance, dirs, dictionary,
            using=using)

    return HttpResponse(content, content_type, status) 
Example #18
Source File: payments.py    From wagtailinvoices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_receipts(invoice, email, amount):
    name = invoice.client_full_name
    id = invoice.id

    # Administrator successful payment receipt
    admin_receipt_message = render_to_string(
        'emails/admin_receipt.txt', {
            'email': email,
            'name': name,
            'amount': amount,
            'id': id,
        })
    admin_receipt = EmailMessage(
        name +
        " has successfully paid",
        admin_receipt_message,
        email,
        [email])
    admin_receipt.content_subtype = 'html'
    admin_receipt.send() 
Example #19
Source File: send_mail_notifications.py    From anytask with MIT License 5 votes vote down vote up
def send_fulltext(domain, from_email):
    notify_messages = []

    for i_message, message in enumerate(
            Message.objects.exclude(
                send_notify_messages__isnull=True
            ).prefetch_related('recipients')
    ):
        notify_messages.append([])
        for user in message.recipients.all():
            if not user.email:
                continue

            user_profile = user.profile
            user_profile.send_notify_messages.remove(message)

            lang = user_profile.language
            translation.activate(lang)

            subject = message.title
            message_text = render_mail(message, user)

            plain_text = strip_tags(message_text).replace(' ', ' ')

            context = {
                "domain": domain,
                "title": subject,
                "message_text": message_text,
            }
            html = render_to_string('email_fulltext_mail.html', context)

            notify_messages[i_message].append((subject, plain_text, html, from_email, [user.email]))

            translation.deactivate()

    return notify_messages 
Example #20
Source File: models.py    From anytask with MIT License 5 votes vote down vote up
def send_mail_update_user(self, email):

        subject = render_to_string('email_update_subject.txt')
        subject = ''.join(subject.splitlines())

        context = {}

        plain_text = render_to_string('email_update.txt', context)
        html = render_to_string('email_update.html', context)

        send_mass_mail_html([(subject, plain_text, html, settings.DEFAULT_FROM_EMAIL, [email])]) 
Example #21
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def new(request, event_id, authorization_target=None):
    if authorization_target is None:
        e = get_object_or_404(
            Incident.authorization.for_user(request.user, 'incidents.handle_incidents'),
            pk=event_id)
    else:
        e = authorization_target

    if request.method == "GET":
        nugget_form = NuggetForm()

    if request.method == 'POST':
        nugget_form = NuggetForm(request.POST)

        if nugget_form.is_valid():
            nugget = nugget_form.save(commit=False)
            nugget.incident = e
            nugget.found_by = request.user
            nugget.save()

            ret = {
                'status': 'success',
                'row': render_to_string("fir_nuggets/nugget_row.html", {'n': nugget, 'mode': 'row', "user": request.user}),
                'raw': render_to_string("fir_nuggets/nugget_row.html", {'n': nugget, 'mode': 'raw', "user": request.user}),
                'nugget_id': nugget.id,
                'mode': 'new',
            }

            e.refresh_artifacts(nugget.raw_data)

            return HttpResponse(dumps(ret), content_type='application/json')
        else:
            errors = render_to_string("fir_nuggets/nugget_form.html", {'mode': 'new', 'nugget_form': nugget_form, 'event_id': e.id})
            ret = {'status': 'error', 'data': errors}
            return HttpResponse(dumps(ret), content_type="application/json")

    return render(request, "fir_nuggets/nugget_form.html", {'nugget_form': nugget_form, 'mode': 'new', 'event_id': event_id}) 
Example #22
Source File: jinja2.py    From django-webpush with GNU General Public License v3.0 5 votes vote down vote up
def webpush_button(self, context, with_class=None):
        template_context = get_templatetag_context(context)
        if with_class:
            template_context['class'] = with_class
        data = render_to_string('webpush_button.html', template_context, using='django')
        return mark_safe(data) 
Example #23
Source File: widgets.py    From django-mdeditor with GNU General Public License v3.0 5 votes vote down vote up
def render(self, name, value, renderer=None, attrs=None):
        """
        renderer: django2.1 新增加的参数,此处不做应用,赋值None做兼容处理
        """
        if value is None:
            value = ''

        final_attrs = self.build_attrs(self.attrs, attrs, name=name)
        return mark_safe(render_to_string('markdown.html', {
            'final_attrs': flatatt(final_attrs),
            'value': conditional_escape(force_text(value)),
            'id': final_attrs['id'],
            'config': self.config,
        })) 
Example #24
Source File: tasks.py    From cride-platzi with MIT License 5 votes vote down vote up
def send_confirmation_email(user_pk):
    """Send account verification link to given user."""
    user = User.objects.get(pk=user_pk)
    verification_token = gen_verification_token(user)
    subject = 'Welcome @{}! Verify your account to start using Comparte Ride'.format(user.username)
    from_email = 'Comparte Ride <noreply@comparteride.com>'
    content = render_to_string(
        'emails/users/account_verification.html',
        {'token': verification_token, 'user': user}
    )
    msg = EmailMultiAlternatives(subject, content, from_email, [user.email])
    msg.attach_alternative(content, "text/html")
    msg.send() 
Example #25
Source File: gmap.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self):
        """
        Generates the JavaScript for the collection of Google Maps in
        this set.
        """
        params = {'js_module': self.js_module,
                  'dom_ids': self.dom_ids,
                  'load_map_js': self.load_map_js(),
                  'icons': self.icons,
                  }
        params.update(self.extra_context)
        return render_to_string(self.template, params) 
Example #26
Source File: shortcuts.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render_to_text(*args, **kwargs):
    "Renders the response using the MIME type for plain text."
    return HttpResponse(loader.render_to_string(*args, **kwargs),
        content_type='text/plain') 
Example #27
Source File: shortcuts.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render_to_kmz(*args, **kwargs):
    """
    Compresses the KML content and returns as KMZ (using the correct
    MIME type).
    """
    return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)),
        content_type='application/vnd.google-earth.kmz') 
Example #28
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self, name, value, attrs=None):
        # If a string reaches here (via a validation error on another
        # field) then just reconstruct the Geometry.
        if isinstance(value, six.string_types):
            value = self.deserialize(value)

        if value:
            # Check that srid of value and map match
            if value.srid != self.map_srid:
                try:
                    ogr = value.ogr
                    ogr.transform(self.map_srid)
                    value = ogr
                except gdal.GDALException as err:
                    logger.error(
                        "Error transforming geometry from srid '%s' to srid '%s' (%s)" % (
                            value.srid, self.map_srid, err)
                    )

        context = self.build_attrs(
            attrs,
            name=name,
            module='geodjango_%s' % name.replace('-', '_'),  # JS-safe
            serialized=self.serialize(value),
            geom_type=gdal.OGRGeomType(self.attrs['geom_type']),
            STATIC_URL=settings.STATIC_URL,
            LANGUAGE_BIDI=translation.get_language_bidi(),
        )
        return loader.render_to_string(self.template_name, context) 
Example #29
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self, name, value, *args, **kwargs):
        from django.contrib.admin.views.main import IS_POPUP_VAR, TO_FIELD_VAR
        rel_opts = self.rel.to._meta
        info = (rel_opts.app_label, rel_opts.model_name)
        self.widget.choices = self.choices
        url_params = '&'.join("%s=%s" % param for param in [
            (TO_FIELD_VAR, self.rel.get_related_field().name),
            (IS_POPUP_VAR, 1),
        ])
        context = {
            'widget': self.widget.render(name, value, *args, **kwargs),
            'name': name,
            'url_params': url_params,
            'model': rel_opts.verbose_name,
        }
        if self.can_change_related:
            change_related_template_url = self.get_related_url(info, 'change', '__fk__')
            context.update(
                can_change_related=True,
                change_related_template_url=change_related_template_url,
            )
        if self.can_add_related:
            add_related_url = self.get_related_url(info, 'add')
            context.update(
                can_add_related=True,
                add_related_url=add_related_url,
            )
        if self.can_delete_related:
            delete_related_template_url = self.get_related_url(info, 'delete', '__fk__')
            context.update(
                can_delete_related=True,
                delete_related_template_url=delete_related_template_url,
            )
        return mark_safe(render_to_string(self.template, context)) 
Example #30
Source File: email.py    From djreservation with GNU General Public License v3.0 5 votes vote down vote up
def send_html_email(subject, template, context=None):
    if context is None:
        context = {}
    reservation = context['reservation']
    message = render_to_string(template,
                               context)
    send_mail(
        subject=subject,
        message=_('Please, use an email with html support'),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[reservation.user.email],
        fail_silently=True,
        html_message=message
    )