def urls(self): "Returns a list of (value, URL) tuples." # First, check the urls() method for each plugin. plugin_urls = [] for plugin_name, plugin in self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) if urls is not None: #plugin_urls.append(urls) values = self.values() return zip(self.values(), urls) if self.field.rel: m = EasyModel(self.model.site, self.field.rel.to) if self.field.rel.to in self.model.model_list: lst = [] for value in self.values(): if value is None: continue url = mark_safe('%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val()))) lst.append((smart_unicode(value), url)) else: lst = [(value, None) for value in self.values()] elif self.field.choices: lst = [] for value in self.values(): url = mark_safe('%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value))) lst.append((value, url)) elif isinstance(self.field, models.URLField): val = self.values()[0] lst = [(val, iri_to_uri(val))] else: lst = [(self.values()[0], None)] return lst
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 my_django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) if f.template_name: t = loader.select_template((f.template_name, DEFAULT_TEMPLATE)) else: t = 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) c = RequestContext(request, { 'flatpage': f, }) response = HttpResponse(t.render(c)) populate_xheaders(request, response, FlatPage, f.id) return response
def paginator_number(cl, i): """ Generates an individual page index link in a paginated list. """ if i == DOT: return u'... ' elif i == cl.page_num: return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1)) else: return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(cl.get_query_string({PAGE_VAR: i})), (i == cl.paginator.num_pages - 1 and ' class="end"' or ''), i + 1))
def render(self, name, value, attrs=None): rel_to = self.rel.to if attrs is None: attrs = {} extra = [] if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( 'admin:%s_%s_changelist' % (rel_to._meta.app_label, rel_to._meta.module_name), current_app=self.admin_site.name) params = self.url_parameters() if params: url = u'?' + u'&'.join( [u'%s=%s' % (k, v) for k, v in params.items()]) else: url = u'' if "class" not in attrs: attrs[ 'class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append( u'<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % (related_url, url, name)) extra.append( u'<img src="%s" width="16" height="16" alt="%s" /></a>' % (static('admin/img/selector-search.gif'), _('Lookup'))) output = [ super(ForeignKeyRawIdWidget, self).render(name, value, attrs) ] + extra if value: output.append(self.label_for_value(value)) return mark_safe(u''.join(output))
def contents(self): from my_django.contrib.admin.templatetags.admin_list import _boolean_icon from my_django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field(field, obj, model_admin) except (AttributeError, ValueError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: boolean = getattr(attr, "boolean", False) if boolean: result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) if getattr(attr, "allow_tags", False): result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE elif isinstance(f.rel, ManyToManyRel): result_repr = ", ".join(map(unicode, value.all())) else: result_repr = display_for_field(value, f) return conditional_escape(result_repr)
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 mark_safe(escape(value))
def safeseq(value): """ A "safe" filter for sequences. Marks each element in the sequence, individually, as safe, after converting them to unicode. Returns a list with the results. """ return [mark_safe(force_unicode(obj)) for obj in value]
def super(self): render_context = self.context.render_context if (BLOCK_CONTEXT_KEY in render_context and render_context[BLOCK_CONTEXT_KEY].get_block( self.name) is not None): return mark_safe(self.render(self.context)) return ''
def tag(self): if 'id' in self.attrs: self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index) final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value) if self.is_checked(): final_attrs['checked'] = 'checked' return mark_safe(u'<input%s />' % flatatt(final_attrs))
def render(self, name, value, attrs): encoded = value if not is_password_usable(encoded): return "None" final_attrs = self.build_attrs(attrs) encoded = smart_str(encoded) if len(encoded) == 32 and '$' not in encoded: algorithm = 'unsalted_md5' else: algorithm = encoded.split('$', 1)[0] try: hasher = get_hasher(algorithm) except ValueError: summary = "<strong>Invalid password format or unknown hashing algorithm.</strong>" else: summary = "" for key, value in hasher.safe_summary(encoded).iteritems(): summary += "<strong>%(key)s</strong>: %(value)s " % {"key": ugettext(key), "value": value} return mark_safe("<div%(attrs)s>%(summary)s</div>" % {"attrs": flatatt(final_attrs), "summary": summary})
def _boolean_icon(field_val): icon_url = static('admin/img/icon-%s.gif' % { True: 'yes', False: 'no', None: 'unknown' }[field_val]) return mark_safe(u'<img src="%s" alt="%s" />' % (icon_url, field_val))
def as_table(self): "Returns this formset rendered as HTML <tr>s -- excluding the <table></table>." # XXX: there is no semantic division between forms here, there # probably should be. It might make sense to render each form as a # table row with each field as a td. forms = u' '.join([form.as_table() for form in self]) return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': # Only add the 'value' attribute if a value is non-empty. final_attrs['value'] = force_unicode(self._format_value(value)) return mark_safe(u'<input%s />' % flatatt(final_attrs))
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return mark_safe(re.sub('[-\s]+', '-', value))
def _dec(*args, **kwargs): if args: args = list(args) args[0] = force_unicode(args[0]) if (isinstance(args[0], SafeData) and getattr(_dec._decorated_function, 'is_safe', False)): return mark_safe(func(*args, **kwargs)) return func(*args, **kwargs)
def linebreaks_filter(value, autoescape=None): """ Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br />``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape))
def html(self): ''' Возвращает HTML-текст статьи, полученный фильтрацией содержимого через указанный фильтр. ''' if self.filter in filters: result = filters[self.filter](self.text) else: result = linebreaks(escape(self.text)) return mark_safe(result) soup = BeautifulSoup(result) def urlify(s): s = re.sub(WWW_PATTERN, r'\1http://www.', s) s = re.sub(FTP_PATTERN, r'\1ftp://ftp.', s) s = re.sub(PROTOCOL_PATTERN, r'<a href="\1\2">\1\2</a>\3\4', s) return BeautifulSoup(s) def has_parents(node, tags): if node is None: return False return node.name in tags or has_parents(node.parent, tags) text_chunks = [ c for c in soup.recursiveChildGenerator() if isinstance(c, unicode) ] for chunk in text_chunks: s = chunk if not has_parents(chunk.parent, ['code']): s = re.sub(ur'\B--\B', u'—', s) if not has_parents(chunk.parent, ['a', 'code']): s = urlify(s) chunk.replaceWith(s) for link in soup.findAll('a'): if 'rel' in link: link['rel'] += ' ' else: link['rel'] = '' link['rel'] += 'nofollow' result = unicode(soup) return mark_safe(result)
def render(self, context): bits = [] for node in self: if isinstance(node, Node): bit = self.render_node(node, context) else: bit = node bits.append(force_unicode(bit)) return mark_safe(u''.join(bits))
def render(self, name, value, attrs=None, choices=()): if value is None: value = [] final_attrs = self.build_attrs(attrs, name=name) output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] options = self.render_options(choices, value) if options: output.append(options) output.append('</select>') return mark_safe(u'\n'.join(output))
def render(self, context): old_setting = context.autoescape context.autoescape = self.setting output = self.nodelist.render(context) context.autoescape = old_setting if self.setting: return mark_safe(output) else: return output
def cut(value, arg): """ Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) value = value.replace(arg, u'') if safe and arg != ';': return mark_safe(value) return value
def render(self, name=None, value=None, attrs=None, choices=()): name = name or self.name value = value or self.value attrs = attrs or self.attrs if 'id' in self.attrs: label_for = ' for="%s_%s"' % (self.attrs['id'], self.index) else: label_for = '' choice_label = conditional_escape(force_unicode(self.choice_label)) return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
def urls(self, plugin_name, easy_instance_field): if isinstance(easy_instance_field.field, models.DateField): d = easy_instance_field.raw_value return [ mark_safe( u'%s%s/%s/%s/%s/%s/' % (easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, str(d.year), datetime_safe.new_date(d).strftime('%b').lower(), d.day)) ]
def render(self, context): csrf_token = context.get('csrf_token', None) if csrf_token: if csrf_token == 'NOTPROVIDED': return mark_safe(u"") else: return mark_safe( u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning from my_django.conf import settings if settings.DEBUG: import warnings warnings.warn( "A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext." ) return u''
def get_admin_url(self): """ Returns the admin URL to edit the object represented by this log entry. This is relative to the Django admin index page. """ if self.content_type and self.object_id: return mark_safe(u"%s/%s/%s/" % (self.content_type.app_label, self.content_type.model, quote(self.object_id))) return None
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 label_tag(self): attrs = {} if not self.is_first: attrs["class"] = "inline" label = self.field['label'] contents = capfirst(force_unicode(escape(label))) + u":" return mark_safe('<label%(attrs)s>%(contents)s</label>' % { "attrs": flatatt(attrs), "contents": contents, })
def urls(self, plugin_name, easy_instance_field): if easy_instance_field.field in self.field_dict( easy_instance_field.model.model).values(): field_value = smart_str(easy_instance_field.raw_value) return [ mark_safe(u'%s%s/%s/%s/' % (easy_instance_field.model.url(), plugin_name, easy_instance_field.field.name, urllib.quote(field_value, safe=''))) ]
def join(value, arg, autoescape=None): """ Joins a list with a string, like Python's ``str.join(list)``. """ value = map(force_unicode, value) if autoescape: value = [conditional_escape(v) for v in value] try: data = conditional_escape(arg).join(value) except AttributeError: # fail silently but nicely return value return mark_safe(data)
def urlizetrunc(value, limit, autoescape=None): """ Converts URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe( urlize_impl(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape))