我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用django.template.loader.render_to_string()。
def send_share_notification(share_id): """Super simple you're content has been shared notification to a user.""" if settings.DEBUG: return try: content = Content.objects.get(id=share_id, content_type=ContentType.SHARE, share_of__local=True) except Content.DoesNotExist: logger.warning("No share content found with id %s", share_id) return content_url = "%s%s" % (settings.SOCIALHOME_URL, content.share_of.get_absolute_url()) subject = _("New share of: %s" % content.share_of.short_text_inline) context = get_common_context() context.update({ "subject": subject, "actor_name": content.author.name_or_handle, "actor_url": "%s%s" % (settings.SOCIALHOME_URL, content.author.get_absolute_url()), "content_url": content_url, "name": content.share_of.author.name_or_handle, }) send_mail( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), render_to_string("notifications/share.txt", context=context), settings.DEFAULT_FROM_EMAIL, [content.share_of.author.user.email], fail_silently=False, html_message=render_to_string("notifications/share.html", context=context), )
def send(self, request): if (not self.last_email) or self.last_email + timedelta(hours=12) < now(): # TODO: TIMEDELTA mit config old_lang = translation.get_language() translation.activate(self.user.language) link = reverse('poll_vote', args=(self.poll.url,)) # TODO: hier direkt das poll oder das Vote? email_content = render_to_string('invitations/mail_invite.txt', { 'receiver': self.user.username, 'creator': self.creator.username, 'link': link }) try: send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email]) self.last_email = now() self.save() except SMTPRecipientsRefused: translation.activate(old_lang) messages.error( request, _("The mail server had an error sending the notification to {}".format(self.user.username)) ) translation.activate(old_lang) else: messages.error( request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username)) )
def render(self): """Renders the tab to HTML using the :meth:`~horizon.tabs.Tab.get_context_data` method and the :meth:`~horizon.tabs.Tab.get_template_name` method. If :attr:`~horizon.tabs.Tab.preload` is ``False`` and ``force_load`` is not ``True``, or either :meth:`~horizon.tabs.Tab.allowed` or :meth:`~horizon.tabs.Tab.enabled` returns ``False`` this method will return an empty string. """ if not self.load: return '' try: context = self.data except exceptions.Http302: raise except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() raise six.reraise(TemplateSyntaxError, exc_value, exc_traceback) return render_to_string(self.get_template_name(self.request), context)
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()
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)
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
def send_email(to, kind, **kwargs): current_site = Site.objects.get_current() ctx = { "current_site": current_site, "STATIC_URL": settings.STATIC_URL, } ctx.update(kwargs.get("context", {})) subject = "[%s] %s" % ( current_site.name, render_to_string("emails/%s/subject.txt" % kind, ctx).strip() ) message_html = render_to_string("emails/%s/message.html" % kind, ctx) message_plaintext = strip_tags(message_html) from_email = settings.DEFAULT_FROM_EMAIL email = EmailMultiAlternatives(subject, message_plaintext, from_email, to) email.attach_alternative(message_html, "text/html") email.send()
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): if hasattr(self, 'wrapper_class'): context['wrapper_class'] = self.wrapper_class if self.attrs: if 'detail-class' in self.attrs: context['input_class'] = self.attrs['detail-class'] elif 'class' in self.attrs: context['input_class'] = self.attrs['class'] html = '' for field, result in self.results: context['result'] = result if field in form.fields: if form.fields[field].widget != forms.HiddenInput: context['field'] = form[field] html += loader.render_to_string(self.template, context) else: context['field'] = field html += loader.render_to_string(self.template, context) return html
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}))
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}))
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
def run(self, user_id): user = get_user_model().objects.get(pk=user_id) # Send email to only user who has email except for TEST_EMAIL if user.email and user.email != settings.TEST_EMAIL: send_email( sender=self.email_sender, receiver=user.email, subject=self.email_subject.format( username=user.username ), html=render_to_string( self.email_template, context={ "username": user.username, "verification_key": user.profile.verification_key, }, ), )
def run(self): for user in get_user_model().objects.agree_email_notification(): if not user.today_diary and user.is_verified: send_email( sender=settings.ADMIN_SENDER_EMAIL, receiver=user.email, subject=settings.WRITE_DIARY_EMAIL_SUBJECT.format( username=user.username, ), html=render_to_string( "emails/write_diary.html", context={ "username": user.username, }, ), )
def _notify_reviewers(self, start, end, reports): """Notify reviewers on their unverified reports.""" User = get_user_model() reviewers = User.objects.all_reviewers().filter(email__isnull=False) subject = '[Timed] Verification of reports' from_email = settings.DEFAULT_FROM_EMAIL mails = [] for reviewer in reviewers: if reports.filter(task__project__reviewers=reviewer).exists(): body = render_to_string( 'mail/notify_reviewers_unverified.txt', { # we need start and end date in system format 'start': str(start), 'end': str(end), 'reviewer': reviewer, 'protocol': settings.HOST_PROTOCOL, 'domain': settings.HOST_DOMAIN, }, using='text' ) mails.append((subject, body, from_email, [reviewer.email])) if len(mails) > 0: send_mass_mail(mails)
def render(self, name, value, attrs=None): w, h = getattr(settings, 'WAGTAILCLOUDINARY_ADMIN_IMAGE_SIZE', (165, 165)) if isinstance(value, str): value = str_to_cloudinary_resource(value) admin_image_version = 'w_{},h_{},c_fill'.format(w, h) context = { 'widget': { 'name': name, 'value': value }, 'image': value, 'width': w, 'height': h, 'admin_image_version': admin_image_version, } return render_to_string("wagtailcloudinary/include/input.html", context)
def browse(self, request): params = {'max_results': 18, 'tags': True} if 'next' in request.GET: params['next_cursor'] = request.GET['next'] tag = request.GET.get('tag', None) if tag: context = cloudinary.api.resources_by_tag(tag, **params) else: context = cloudinary.api.resources(**params) context['admin_image_version'] = self.admin_image_version if 'next' in request.GET or 'tag' in request.GET: template_name = 'wagtailcloudinary/include/browse_ajax.html' html = render_to_string(template_name, context) return JsonResponse({'html': html, 'next': context.get('next_cursor', None), 'tag': tag}) else: tags = cloudinary.api.tags() context.update(tags) template_name = 'wagtailcloudinary/browse.html' return render_modal_workflow(request, template_name, 'wagtailcloudinary/browse.js', context)
def send_follow_notification(follower_id, followed_id): """Super simple you've been followed notification to a user.""" if settings.DEBUG: return try: user = User.objects.get(profile__id=followed_id, is_active=True) except User.DoesNotExist: logger.warning("No active user with profile %s found for follow notification", followed_id) return try: follower = Profile.objects.get(id=follower_id) except Profile.DoesNotExist: logger.warning("No follower profile %s found for follow notifications", follower_id) return logger.info("send_follow_notification - Sending mail to %s", user.email) subject = _("New follower: %s" % follower.handle) context = get_common_context() context.update({ "subject": subject, "actor_name": follower.name_or_handle, "actor_url": "%s%s" % (settings.SOCIALHOME_URL, follower.get_absolute_url()), "name": user.profile.name_or_handle, }) send_mail( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), render_to_string("notifications/follow.txt", context=context), settings.DEFAULT_FROM_EMAIL, [user.email], fail_silently=False, html_message=render_to_string("notifications/follow.html", context=context), )
def send_reply_notifications(content_id): """Super simple reply notification to content local participants. Until proper notifications is supported, just pop out an email. """ if settings.DEBUG: return try: content = Content.objects.get(id=content_id, content_type=ContentType.REPLY) except Content.DoesNotExist: logger.warning("No reply content found with id %s", content_id) return root_content = content.root exclude_user = content.author.user if content.local else None participants = get_root_content_participants(root_content, exclude_user=exclude_user) if not participants: return subject = _("New reply to: %s" % root_content.short_text_inline) # TODO use fragment url to reply directly when available content_url = "%s%s" % (settings.SOCIALHOME_URL, root_content.get_absolute_url()) context = get_common_context() context.update({ "subject": subject, "actor_name": content.author.name_or_handle, "actor_url": "%s%s" % (settings.SOCIALHOME_URL, content.author.get_absolute_url()), "reply_text": content.text, "reply_rendered": content.rendered, "reply_url": content_url, }) for participant in participants: context["name"] = participant.profile.name_or_handle logger.info("send_reply_notifications - Sending mail to %s", participant.email) send_mail( "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), render_to_string("notifications/reply.txt", context=context), settings.DEFAULT_FROM_EMAIL, [participant.email], fail_silently=False, html_message=render_to_string("notifications/reply.html", context=context), )
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["bookmarklet"] = render_to_string("content/bookmarklet.min.js", {}, request=self.request) context["is_reply"] = self.is_reply return context
def _get_text_initial_from_parameters(self): parameters = {} if self.request.GET.get("url"): parameters["url"] = self.request.GET.get("url") if self.request.GET.get("title"): parameters["title"] = self.request.GET.get("title") if self.request.GET.get("notes"): parameters["notes"] = self.request.GET.get("notes") if parameters: return render_to_string("content/_bookmarklet_initial.html", parameters, request=self.request)
def test_get_initial(self): request = RequestFactory().get("/") view = self.get_instance(ContentCreateView, request=request) initial = view.get_initial() self.assertIsNone(initial.get("text")) view.request = RequestFactory().get("/?url=url&title=title¬es=notes&dummy=dummy") initial = view.get_initial() self.assertEqual(initial.get("text"), render_to_string("content/_bookmarklet_initial.html", { "title": "title", "notes": "notes", "url": "url", }))
def test_template(self): template = render_to_string("content/_bookmarklet_initial.html", { "title": "a title", "url": "the url", "notes": "some notes", }) self.assertEqual(template, "### a title\n\n> some notes\n\nthe url\n") template = render_to_string("content/_bookmarklet_initial.html", { "title": "a title", }) self.assertEqual(template, "### a title\n") template = render_to_string("content/_bookmarklet_initial.html", { "title": "a title", "url": "the url", }) self.assertEqual(template, "### a title\n\nthe url\n") template = render_to_string("content/_bookmarklet_initial.html", { "url": "the url", }) self.assertEqual(template, "the url\n") template = render_to_string("content/_bookmarklet_initial.html", { "url": "the url", "notes": "some notes", }) self.assertEqual(template, "> some notes\n\nthe url\n") template = render_to_string("content/_bookmarklet_initial.html", { "notes": "some notes", }) self.assertEqual(template, "> some notes\n") template = render_to_string("content/_bookmarklet_initial.html", { "title": "a title", "notes": "some notes", }) self.assertEqual(template, "### a title\n\n> some notes\n")
def sitemap(request): """Simple XML sitemap view.""" sitemap_content = cache.get(cachekeys.SITEMAP_CONTENT) if sitemap_content is None: sitemap_content = render_to_string( 'powerpages/sitemap.xml', context={'urlset': sitemap_config.sitemaps.urls(request)}, request=request ) cache.get(cachekeys.SITEMAP_CONTENT, sitemap_content) return http.HttpResponse(sitemap_content, content_type='application/xml')
def restore_account(username, temp_password, recipient): """ Celery task for sending mail on restore user data. :param str username: The restored username. :param str temp_password: The temporary password for restored username. :param str recipient: The mail recipient. """ html_content = render_to_string('mails/account_restore.html', {'username': username, 'password': temp_password}) text_content = strip_tags(html_content) subject = '?????????????? ????????' email = EmailMultiAlternatives(subject, text_content, to=[recipient]) email.attach_alternative(html_content, 'text/html') email.send() # ----------------------------------------------------------------------------------------------------------------------
def changed_password(username, recipient): """ Celery task for sending mail, to notify user about password changed. :param str username: The restored username. :param str recipient: The mail recipient. """ html_content = render_to_string('mails/password_changed.html', {'username': username}) text_content = strip_tags(html_content) subject = '????????? ?????? ????????' email = EmailMultiAlternatives(subject, text_content, to=[recipient]) email.attach_alternative(html_content, 'text/html') email.send() # ----------------------------------------------------------------------------------------------------------------------
def get_bookmarklet_url(request): scheme = 'http' if settings.DEBUG else 'https' host = request.META['HTTP_HOST'] return mark_safe('javascript:' + render_to_string( 'bookmarklet.js', { 'base_url': f'{scheme}://{host}' }, request=request ).replace('\n', '').replace('"', '"'))
def send(self, request, vote: Vote): old_lang = translation.get_language() translation.activate(self.user.language) link = reverse('poll', args=(self.poll.url,)) if vote.anonymous: username = _("Annonymus") elif vote.user: username = vote.user.username else: username = vote.name email_content = render_to_string('poll/mail_watch.txt', { 'receiver': self.user.username, 'user': username if self.poll.show_results == "complete" else _("by an user"), 'poll': self.poll.title, 'link': link, 'hide_participants': self.poll.hide_participants # TODO: simplify merge with usernameshadowing above }) try: send_mail(_("New votes for {}".format(self.poll.title)), email_content, None, [self.user.email]) except SMTPRecipientsRefused: translation.activate(old_lang) messages.error( request, _("The mail server had an error sending the notification to {}".format( self.user.username)) ) translation.activate(old_lang)
def _verify_email(request, email): token = signing.dumps({ 'email': email, 'username': request.user.username, }) url_path = reverse('registration_change_email', args=(token,)) link = request.build_absolute_uri(url_path) email_content = render_to_string('registration/email_verify.txt', { 'username': request.user.username, 'email': email, 'link': link, }) return _send_mail_or_error_page(_('Verify this address for %s' % settings.SITE_NAME), email_content, email, request)
def _finish_account_request(request, info): email = info['email'] token = signing.dumps(info) url_path = reverse('registration_create_account', args=(token,)) activation_link = request.build_absolute_uri(url_path) email_content = render_to_string('registration/create_email.txt', { 'activation_link': activation_link }) return _send_mail_or_error_page(_('Account creation at %s' % settings.SITE_NAME), email_content, email, request)
def active_email(request, user): message = render_to_string('email/active_email.txt', { 'user': user, 'domain': request.get_host(), 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) subject = 'Activate your blog account.' to_email = user.email send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list=[to_email])
def render_html(html_id, url): context = dict(html_id=html_id, url=url) return render_to_string('charting/async/html.html', context)
def render_js(html_id, url): context = dict(html_id=html_id, url=url) return render_to_string('charting/async/js.html', context)
def render_chart_async(url_name, *args, **kwargs): html_id = 'chart-{}'.format(uuid.uuid4()) url = reverse(url_name, args=args, kwargs=kwargs) context = { 'html': render_html(html_id, url), 'js': render_js(html_id, url), } return render_to_string('charting/chart.html', context)
def as_html(self, *args, **kwargs): context = { 'html_id': self._gen_html_id(), 'chart': self, 'chart_configuration': self.get_configuration(*args, **kwargs), } context = { 'html': self.render_html(context), 'js': self.render_js(context), } return render_to_string('charting/chart.html', context)
def render_js(self, context): return render_to_string('charting/js.html', context)