def force_escape(value): """ Escapes a string's HTML. This returns a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value)
def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return ' <strong>%s</strong>' % escape(Truncator(obj).words(14, truncate='...')) except (ValueError, self.rel.to.DoesNotExist): return ''
def humanize_tester(self, test_list, result_list, method): # Using max below ensures we go through both lists # However, if the lists are not equal length, this raises an exception for test_content, result in zip(test_list, result_list): t = Template('{%% load humanize %%}{{ test_content|%s }}' % method) rendered = t.render(Context(locals())).strip() self.assertEqual(rendered, escape(result), msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result))
def linebreaksbr(value, autoescape=None): """ Converts all newlines in a piece of plain text to HTML line breaks (``<br />``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(value.replace('\n', '<br />'))
def get_template_exception_info(self): origin, (start, end) = self.exc_value.django_template_source template_source = origin.reload() context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(template_source)): if start >= upto and end <= next: line = num before = escape(template_source[upto:start]) during = escape(template_source[start:end]) after = escape(template_source[end:next]) source_lines.append( (num, escape(template_source[upto:next])) ) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases, exc_value.args might be empty. try: message = self.exc_value.args[0] except IndexError: message = '(Could not get exception message)' self.template_info = { 'message': message, 'source_lines': source_lines[top:bottom], 'before': before, 'during': during, 'after': after, 'top': top, 'bottom': bottom, 'total': total, 'line': line, 'name': origin.name, }
def linenumbers(value, autoescape=None): """Displays text with line numbers.""" lines = value.split('\n') # Find the maximum width of the line count, for use with zero padding # string format command width = six.text_type(len(six.text_type(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return mark_safe('\n'.join(lines))
def _render_value_in_context(value, context): """ Converts any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a unicode object. If value is a string, it is expected to have already been translated. """ value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) value = force_text(value) if ((context.autoescape and not isinstance(value, SafeData)) or isinstance(value, EscapeData)): return escape(value) else: return value
def render(self, context): try: output = self.filter_expression.resolve(context) output = template_localtime(output, use_tz=context.use_tz) output = localize(output, use_l10n=context.use_l10n) output = force_text(output) except UnicodeDecodeError: return '' except Exception as e: if not hasattr(e, 'django_template_source'): e.django_template_source = self.source raise if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData): return escape(output) else: return output
def user_change_password(self, request, id, form_url=''): if not self.has_change_permission(request): raise PermissionDenied user = get_object_or_404(self.queryset(request), pk=id) if request.method == 'POST': form = self.change_password_form(user, request.POST) if form.is_valid(): form.save() msg = ugettext('Password changed successfully.') messages.success(request, msg) return HttpResponseRedirect('..') else: form = self.change_password_form(user) fieldsets = [(None, {'fields': list(form.base_fields)})] adminForm = admin.helpers.AdminForm(form, fieldsets, {}) context = { 'title': _('Change password: %s') % escape(user.username), 'adminForm': adminForm, 'form_url': form_url, 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'opts': self.model._meta, 'original': user, 'save_as': False, 'show_save': True, } return TemplateResponse(request, [ self.change_user_password_template or 'admin/auth/user/change_password.html' ], context, current_app=self.admin_site.name)
def test_no_textile(self): t = Template("{% load markup %}{{ textile_content|textile }}") rendered = t.render(Context({'textile_content':self.textile_content})).strip() self.assertEqual(rendered, escape(self.textile_content))
def assertContainsEscaped(self, response, text, **kwargs): return self.assertContains(response, escape(force_text(text)), **kwargs)
def post_comment(request, next=None, using=None): """ Post a comment. HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are errors a preview template, ``comments/preview.html``, will be rendered. """ # Fill out some initial data fields from an authenticated user, if present data = request.POST.copy() if request.user.is_authenticated(): if not data.get('name', ''): data["name"] = request.user.get_full_name() or request.user.username if not data.get('email', ''): data["email"] = request.user.email # Check to see if the POST data overrides the view's next argument. next = data.get("next", next) # Look up the object we're trying to comment about ctype = data.get("content_type") object_pk = data.get("object_pk") if ctype is None or object_pk is None: return CommentPostBadRequest("Missing content_type or object_pk field.") try: model = models.get_model(*ctype.split(".", 1)) target = model._default_manager.using(using).get(pk=object_pk) except TypeError: return CommentPostBadRequest( "Invalid content_type value: %r" % escape(ctype)) except AttributeError: return CommentPostBadRequest( "The given content-type %r does not resolve to a valid model." % \ escape(ctype)) except ObjectDoesNotExist: return CommentPostBadRequest( "No object matching content-type %r and object PK %r exists." % \ (escape(ctype), escape(object_pk))) except (ValueError, ValidationError) as e: return CommentPostBadRequest( "Attempting go get content-type %r and object PK %r exists raised %s" % \ (escape(ctype), escape(object_pk), e.__class__.__name__)) # Do we want to preview the comment? preview = "preview" in data # Construct the comment form form = comments.get_form()(target, data=data) # Check security information if form.security_errors(): return CommentPostBadRequest( "The comment form failed security verification: %s" % \ escape(str(form.security_errors()))) # If there are errors or if we requested a preview show the comment if form.errors or preview: template_list = [ # These first two exist for purely historical reasons. # Django v1.0 and v1.1 allowed the underscore format for # preview templates, so we have to preserve that format. "comments/%s_%s_preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s_preview.html" % model._meta.app_label, # Now the usual directory based template hierarchy. "comments/%s/%s/preview.html" % (model._meta.app_label, model._meta.module_name), "comments/%s/preview.html" % model._meta.app_label, "comments/preview.html", ] return render_to_response( template_list, { "comment" : form.data.get("comment", ""), "form" : form, "next": next, }, RequestContext(request, {}) ) # Otherwise create the comment comment = form.get_comment_object() comment.ip_address = request.META.get("REMOTE_ADDR", None) if request.user.is_authenticated(): comment.user = request.user # Signal that the comment is about to be saved responses = signals.comment_will_be_posted.send( sender = comment.__class__, comment = comment, request = request ) for (receiver, response) in responses: if response == False: return CommentPostBadRequest( "comment_will_be_posted receiver %r killed the comment" % receiver.__name__) # Save the comment and signal that it was saved comment.save() signals.comment_was_posted.send( sender = comment.__class__, comment = comment, request = request ) return next_redirect(data, next, comment_done, c=comment._get_pk_val())
def item_title(self, item): # Titles should be double escaped by default (see #6533) return escape(force_text(item))