def test_render_to_string(): # [bug] Test that the values given directly do overwrite does that # are already exist in the given context_instance. Due to a bug this # was previously not the case. from django.template import Context from coffin.template.loader import render_to_string assert render_to_string('render-x.html', {'x': 'new'}, context_instance=Context({'x': 'old'})) == 'new' # [bug] Test that the values from context_instance actually make it # into the template. assert render_to_string('render-x.html', context_instance=Context({'x': 'foo'})) == 'foo' # [bug] Call without the optional ``context_instance`` argument works assert render_to_string('render-x.html', {'x': 'foo'}) == 'foo' # ``dictionary`` argument may be a Context instance assert render_to_string('render-x.html', Context({'x': 'foo'})) == 'foo' # [bug] Both ``dictionary`` and ``context_instance`` may be # Context objects assert render_to_string('render-x.html', Context({'x': 'foo'}), context_instance=Context()) == 'foo'
def validate(self): """ Compiles the page and sets valid and error flags depending on the result. Saves the version. """ self.valid = False try: # ToDo: поправить тут request = HttpRequest() request.user = AnonymousUser() context = RequestContext(request) render_to_string(self.page.template, yaml.load(self.data), context_instance=context) self.valid = True self.error = "" except (TemplateError, YAMLError), error: self.error = "line %s: %s" % (str(getattr(error, 'lineno', 'unknown')), str(error))
def render_to_string(template_name, context={}, context_instance=None, response_format='html'): "Picks up the appropriate template to render to string" if not response_format or 'pdf' in response_format or not response_format in settings.HARDTREE_RESPONSE_FORMATS: response_format = 'html' if not ("." + response_format) in template_name: template_name += "." + response_format template_name = response_format + "/" + template_name context['response_format'] = response_format if context_instance: context['site_domain'] = RequestSite(context_instance['request']).domain context = _preprocess_context_html(context) if (settings.DEBUG_HACK): f = open("/tmp/debug_hack.txt", "a") f.write("***TEMPLATE***: \n") f.write(template_name + "\n") f.write("***context***: \n") f.write(str(context) + "\n") f.write("***context_instance***: \n") f.write(str(context_instance) + "\n") f.write("*********************************************************************\n") f.close() rendered_string = loader.render_to_string(template_name, context, context_instance) return rendered_string
def json_template(data, template_name, template_context): """Old style, use JSONTemplateResponse instead of this. """ html = render_to_string(template_name, template_context) data = data or {} data['html'] = html return HttpResponse(json_encode(data), content_type='application/json')
def render_to_string(self, templates, dictionary=None, context_instance=None): dictionary = self.process_context( templates, self.merge_contexts(dictionary, context_instance)) templates = self.prefix_templates(templates, dictionary) return render_to_string(templates, dictionary)
def geo_ip(self): geoip = GeoIP().city(self.request.META['REMOTE_ADDR'] if not self.request.META['REMOTE_ADDR'] == '127.0.0.1' else '99.153.72.100') return { 'lat': geoip['latitude'], 'lng': geoip['longitude'], 'content': render_to_string('jimross/info-home.html', RequestContext(self.request)) }
def server_error(request, template_name='500.html'): """ 500 error handler. Templates: `500.html` Context: None """ content = render_to_string(template_name, Context({})) return http.HttpResponseServerError(content)
def permission_denied(request, template_name="403.html"): """ Default 403 handler. Templates: `403.html` Context: None """ content = render_to_string(template_name, Context({})) return http.HttpResponseNotFound(content)
def render_to_response(template_name, dictionary=None, context_instance=None): """ :param template_name: Filename of the template to get or a sequence of filenames to try, in order. :param dictionary: Rendering context for the template. :returns: A response object with the evaluated template as a payload. """ rendered = render_to_string(template_name, dictionary, context_instance) return HttpResponse(rendered)
def send_activation(self, user): subject = u'%s%s' % (EMAIL_SUBJECT_PREFIX, 'Account activation') from_email = DEFAULT_FROM_EMAIL to_email = user.email context = {'user': user, 'site': Site.objects.get_current()} text_content = render_to_string('jimross/activation_mail.txt', context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email]) try: html_content = render_to_string('jimross/activation_mail.html', context) msg.attach_alternative(html_content, 'text/html') except TemplateNotFound: pass msg.send()
def render(self, name, value, attrs=None): if value is None: value = '' return render_to_string( 'controller/forms/widgets/scraper_completer.html', { 'name': name, 'value': value, 'scraperwiki_field': self.scraperwiki_field, })
def get_comments_for_object(context, object, next=None): ct = ContentType.objects.get_for_model(object) if ct.id not in CONTENT_TYPES: return "Not supported" comments = api.get_comments(ct.id, object.pk) comments = comments.order_by("-submit_date") initial = {"content_type": ct.id, "object_pk": object.pk, "next": next} form = CommentForm(object, initial=initial) context.update({"comments": comments, "form": form}) return render_to_string("tcc/list-comments.html", context_instance=context)
def _render(self, postfix=None, extra_context=None): from coffin.template.loader import render_to_string postfix = '' if postfix is None else '_%s' % postfix template_location = '/notification/%s%s.html' % ( self.verb.infinitive, postfix) context = self.get_context() if extra_context: context.update(extra_context) html = render_to_string(template_location, context) safe = mark_safe(html) return safe
def page_not_found(request, template_name="404.html"): """ Default 404 handler. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ content = render_to_string(template_name, RequestContext(request, {"request_path": request.path})) return http.HttpResponseNotFound(content)
def _render(self, postfix=None, extra_context=None): from coffin.template.loader import render_to_string postfix = '' if postfix is None else '_%s' % postfix template_location = '/notification/%s%s.html' % (self.verb.infinitive, postfix) context = self.get_context() if extra_context: context.update(extra_context) html = render_to_string(template_location, context) safe = mark_safe(html) return safe
def render_to_response(template_name, dictionary=None, context_instance=None, mimetype=None): """ :param template_name: Filename of the template to get or a sequence of filenames to try, in order. :param dictionary: Rendering context for the template. :returns: A response object with the evaluated template as a payload. """ rendered = render_to_string(template_name, dictionary, context_instance) return HttpResponse(rendered, mimetype=mimetype)
def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ content = render_to_string(template_name, RequestContext(request, {'request_path': request.path})) return http.HttpResponseNotFound(content)
def render(self, name, value, attrs=None): if value is None: value = '' return render_to_string( 'controller/forms/widgets/scraper_completer.html', { 'name': name, 'value': value, 'scraperwiki_field': self.scraperwiki_field, } )
def render_to_response(template_name, context=None, context_instance=None, mimetype=None, status=200, content_type=None): """ :param template_name: Filename of the template to get or a sequence of filenames to try, in order. :param context: Rendering context for the template. :returns: A response object with the evaluated template as a payload. """ if content_type is None: content_type = getattr(settings, 'DEFAULT_CONTENT_TYPE', 'text/html') content = render_to_string(template_name, context, context_instance) return HttpResponse(content, mimetype=mimetype, status=status, content_type=content_type)
def send_sms(template, phone, context=None, *args, **kwargs): """Template-based shortcut to make it consistent with email interface.""" sms_context = default_sms_context.copy() sms_context.update(context or {}) try: rendered = render_to_string(template, sms_context).strip() except TemplateError as e: logger.error(u'Failed to render "{0}" sms for {1}: {2}'.format( template, phone, e)) raise SMSException(e) else: send_sms_raw(phone, rendered, *args, **kwargs)
def render(self, stream=None): ''' Render the pdf with current lines & style ''' # Use a buffer when no stream is given if stream is None: stream = StringIO() # Build lines self.add_days() self.build_lines() # Canvas is landscape oriented pdf = SimpleDocTemplate(stream, pagesize=landscape(letter)) # Table is in a frame table = Table(self.lines, [1.5* inch ] * 7, self.row_heights, style=self.tableStyle, repeatRows=1) table.wrap(0,0) # important hacky way to span on full width tableFrame = Frame(inch / 2, inch / 2, 10*inch, 7*inch) # RunReport logo logo = Image('./medias/img/logo_ligne.png') logo.drawHeight = 2.2*inch*logo.drawHeight / logo.drawWidth logo.drawWidth = 2.2*inch # Plan infos are in a frame, in top left corner context = { 'site' : self.site, 'plan' : self.plan, } title = Paragraph(render_to_string('plan/export.pdf.title.html', context), self.titleStyle) # Add table elements pdf.addPageTemplates([ PageTemplate(id='table', frames=[tableFrame]), ]) story = [ logo, title, Spacer(1, 0.4*inch), # make room for header table, # the plan ] pdf.build(story) if isinstance(stream, StringIO): output = stream.getvalue() stream.close() return output return None
def save(self, domain_override=None, subject_template_name='auth/password_reset_subject.txt', email_template_name='auth/password_reset_email.html', email_template_name_txt='auth/password_reset_email.txt', use_https=False, token_generator=default_token_generator, from_email=None, request=None): """ Generates a one-use only link for resetting password and sends to the user. """ UserModel = get_user_model() email = self.cleaned_data["email"] users = UserModel._default_manager.filter(email__iexact=email) for user in users: # Make sure that no email is sent to a user that actually has # a password marked as unusable if not user.has_usable_password(): continue from django.template import RequestContext request_context = RequestContext(request) c = { 'email': user.email, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', 'SITE_DOMAIN': settings.SITE_DOMAIN, } subject = render_to_string(subject_template_name, c, context_instance=request_context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body_txt = render_to_string(email_template_name_txt, c, context_instance=request_context) if send_html_mail: body_html = render_to_string(email_template_name, c, context_instance=request_context) send_html_mail(subject, body_txt, body_html, from_email, [user.email]) else: send_mail(subject, body_txt, from_email, [user.email])
def edit_comment(request): if request.user.is_anonymous(): raise exceptions.PermissionDenied(_('Sorry, anonymous users cannot edit comments')) comment_id = int(request.POST['comment_id']) try: comment_post = models.Post.objects.get( post_type='comment', pk=comment_id ) except models.Post.DoesNotExist: return HttpResponseNotFound(mimetype="application/json") thread = comment_post.thread if thread and not request.user.has_openode_perm("question_answer_comment_update_any", thread): return HttpResponseForbidden(mimetype="application/json") request.user.edit_comment(comment_post=comment_post, body_text=request.POST['comment']) is_deletable = template_filters.can_delete_comment(comment_post.author, comment_post) is_editable = template_filters.can_edit_comment(comment_post.author, comment_post) tz = ' ' + template_filters.TIMEZONE_STR tz = template_filters.TIMEZONE_STR # show last visit for posts (comments, ...) try: thread_view_last_visit = thread.viewed.get(user=request.user).last_visit except (exceptions.ObjectDoesNotExist, TypeError): thread_view_last_visit = datetime.datetime.now() thread.visit(request.user) return { 'id': comment_post.id, 'object_id': comment_post.parent.id, 'comment_added_at': str(comment_post.added_at.replace(microsecond=0)) + tz, "html": mark_safe(render_to_string("node/snippets/one_comment.html", {"comment": comment_post, "user": request.user, "thread_view_last_visit": thread_view_last_visit, "wrap_content": False})), 'user_display_name': comment_post.author.username, 'user_url': comment_post.author.get_profile_url(), 'user_id': comment_post.author.id, 'is_deletable': is_deletable, 'is_editable': is_editable, 'score': comment_post.points, # to support unchanged js 'points': comment_post.points, 'voted': comment_post.is_upvoted_by(request.user), }
def render_to_string(template_name, context={}, context_instance=None, response_format='html'): "Picks up the appropriate template to render to string" if not response_format or 'pdf' in response_format or not response_format in settings.HARDTREE_RESPONSE_FORMATS: response_format = 'html' if not ("." + response_format) in template_name: template_name += "." + response_format template_name = response_format + "/" + template_name context['response_format'] = response_format if context_instance: context['site_domain'] = RequestSite(context_instance['request']).domain context = _preprocess_context_html(context) rendered_string = loader.render_to_string(template_name, context, context_instance) return rendered_string
def get_comments_for_object(context, object, next=None): ct = ContentType.objects.get_for_model(object) request = context['request'] initial = { 'content_type': ct.id, 'object_pk': object.pk, 'next': next, } form = CommentForm(object, initial=initial) thread_id = request.GET.get('cpermalink', None) if thread_id: comments = api.get_comment_thread(thread_id) else: comments = api.get_comments_limited(ct.id, object.pk) if not comments: comments = [] else: comments = comments.order_by('-sort_date', 'path') context.update({'comments': comments, 'form': form}) return render_to_string('tcc/list-comments.html', context_instance=context)
def get_comments_for_object(context, object, next=None): ct = ContentType.objects.get_for_model(object) request = context['request'] initial = {'content_type': ct.id, 'object_pk': object.pk, 'next': next, } form = CommentForm(object, initial=initial) thread_id = request.GET.get('cpermalink', None) if thread_id: comments = api.get_comment_thread(thread_id) else: comments = api.get_comments_limited(ct.id, object.pk) if not comments: comments = [] else: comments = comments.order_by('-sort_date', 'path') context.update({'comments': comments, 'form': form}) return render_to_string('tcc/list-comments.html', context_instance=context)
def render_to_string(template_name, context=None, context_instance=None, response_format='html'): "Picks up the appropriate template to render to string" if context is None: context = {} if not response_format or 'pdf' in response_format or response_format not in settings.ANAF_RESPONSE_FORMATS: response_format = 'html' if not ("." + response_format) in template_name: template_name += "." + response_format template_name = response_format + "/" + template_name context['response_format'] = response_format if context_instance: context['site_domain'] = RequestSite( context_instance['request']).domain context = _preprocess_context_html(context) rendered_string = loader.render_to_string( template_name, context, context_instance) return rendered_string
def _send_email(template, recipients, context=None): if isinstance(recipients, basestring): recipients = [recipients] mail_context = default_mail_context.copy() mail_context.update(context or {}) try: rendered = render_to_string(template, mail_context).strip() except TemplateError as e: logger.error('Failed to render "{0}" mail for {1}: {2}'.format( template, u', '.join(recipients), e)) raise EmailException(e) subject, message = [token.strip() for token in rendered.split( settings.EMAIL_DELIMITER)] subject = subject.replace('\n', '') from_email = settings.CONTACT_EMAIL msgs = [] for recipient in recipients: msg = EmailMessage(subject, message, from_email=from_email, to=[recipient]) msg.content_subtype = {'txt': 'plain', 'html': 'html'}.get( template.split('.')[-1], 'plain') msgs.append(msg) try: connection = mail.get_connection() connection.send_messages(msgs) connection.close() except Exception as e: logger.error('Failed to send "{0}" mail for {1}: {2}'.format( template, u', '.join(recipients), e)) raise EmailException(e) logger.info('Successfully sent "{0}" mail to {1} recipient(s): {2}'.format( template, len(msgs), u', '.join(recipients)))
def render(request, *args, **kwargs): """ Returns a HttpResponse whose content is filled with the result of calling coffin.template.loader.render_to_string() with the passed arguments. Uses a RequestContext by default. """ httpresponse_kwargs = { 'content_type': kwargs.pop('content_type', None), 'status': kwargs.pop('status', None), } if 'context_instance' in kwargs: context_instance = kwargs.pop('context_instance') if kwargs.get('current_app', None): raise ValueError('If you provide a context_instance you must ' 'set its current_app before calling render()') else: current_app = kwargs.pop('current_app', None) context_instance = RequestContext(request, current_app=current_app) kwargs['context_instance'] = context_instance return HttpResponse(render_to_string(*args, **kwargs), **httpresponse_kwargs)
Get a WordPress sidebar from the blog. """ return wp.method('widgets.get_sidebar', sidebar_id=sidebar_id) @register.object def flatblock(slug, template='flatblocks/flatblock.html'): """ Return a rendered flatblock, using template. """ AUTOCREATE = getattr(settings, 'FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS', False) try: fb = FlatBlock.objects.get(slug=slug) except FlatBlock.DoesNotExist, e: if AUTOCREATE: fb = FlatBlock.objects.create(slug=slug) else: raise return Markup(render_to_string(template, {'flatblock': fb})) @register.object def recent_incidents(count=10): """ Return the `count` most recent incidents. """ return Incident.objects.public().exclude(description='')[:count]
def render_to_string(self, templates, dictionary=None, context_instance=None): dictionary = self.process_context(templates, self.merge_contexts(dictionary, context_instance)) templates = self.prefix_templates(templates, dictionary) return render_to_string(templates, dictionary)
def render_to_string(self, templates, *args, **kwargs): templates = self.prefix_templates(templates) return render_to_string(templates, *args, **kwargs)
""" Get a WordPress sidebar from the blog. """ return wp.method('widgets.get_sidebar', sidebar_id=sidebar_id) @register.object def flatblock(slug, template='flatblocks/flatblock.html'): """ Return a rendered flatblock, using template. """ AUTOCREATE = getattr(settings, 'FLATBLOCKS_AUTOCREATE_STATIC_BLOCKS', False) try: fb = FlatBlock.objects.get(slug=slug) except FlatBlock.DoesNotExist, e: if AUTOCREATE: fb = FlatBlock.objects.create(slug=slug) else: raise return Markup(render_to_string(template, {'flatblock': fb})) @register.object def recent_incidents(count=10): """ Return the `count` most recent incidents. """ return Incident.objects.public().exclude(description='')[:count]
def __generate_comments_json(obj, user, new_comment=None): # non-view generates json data for the post comments """non-view generates json data for the post comments """ models.Post.objects.precache_comments(for_posts=[obj], visitor=user) comments = obj._cached_comments # {"Id":6,"PostId":38589,"CreationDate":"an hour ago","Text":"hello there!","UserDisplayName":"Jarrod Dixon","UserUrl":"/users/3/jarrod-dixon","DeleteUrl":null} json_comments = [] for comment in comments: if user and user.is_authenticated(): try: user.assert_can_delete_comment(comment) #/posts/392845/comments/219852/delete #todo translate this url is_deletable = True except exceptions.PermissionDenied: is_deletable = False is_editable = template_filters.can_edit_comment(comment.author, comment) else: is_deletable = False is_editable = False comment_owner = comment.author tz = ' ' + template_filters.TIMEZONE_STR comment_data = {'id': comment.id, 'object_id': obj.id, 'comment_added_at': str(comment.added_at.replace(microsecond=0)) + tz, 'html': mark_safe(comment.text), 'user_display_name': escape(comment_owner.username), 'user_url': comment_owner.get_profile_url(), 'user_id': comment_owner.id, 'is_deletable': is_deletable, 'is_editable': is_editable, 'points': comment.points, 'score': comment.points, # to support js 'upvoted_by_user': getattr(comment, 'upvoted_by_user', False) } json_comments.append(comment_data) if new_comment: # show last visit for posts (comments, ...) try: thread_view_last_visit = new_comment.thread.viewed.get(user=user).last_visit except (exceptions.ObjectDoesNotExist, TypeError): thread_view_last_visit = datetime.datetime.now() data = simplejson.dumps({ "parent_post_type": new_comment.parent.post_type, "all_comments": json_comments, "html": mark_safe(render_to_string("node/snippets/one_comment.html", { "comment": new_comment, "user": user, "thread_view_last_visit": thread_view_last_visit, "wrap_content": True, })) }) new_comment.thread.visit(user) # add new comment is "activity" a must be reflected new_comment.thread.set_last_activity( last_activity_at=datetime.datetime.now(), last_activity_by=user ) else: data = simplejson.dumps(json_comments) return HttpResponse(data, mimetype="application/json")
def info_dragend(self): return { 'content': render_to_string('jimross/info-dragend.html', RequestContext(self.request)) }