Esempio n. 1
0
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
    """
    Converts any URLs in text into clickable links.

    Works on http://, https://, www. links and links ending in .org, .net or
    .com. Links can have trailing punctuation (periods, commas, close-parens)
    and leading punctuation (opening parens) and it'll still do the right
    thing.

    If trim_url_limit is not None, the URLs in link text longer than this limit
    will truncated to trim_url_limit-3 characters and appended with an elipsis.

    If nofollow is True, the URLs in link text will get a rel="nofollow"
    attribute.

    If autoescape is True, the link text and URLs will get autoescaped.
    """
    trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
    safe_input = isinstance(text, SafeData)
    words = word_split_re.split(force_unicode(text))
    nofollow_attr = nofollow and ' rel="nofollow"' or ''
    for i, word in enumerate(words):
        match = None
        if '.' in word or '@' in word or ':' in word:
            match = punctuation_re.match(word)
        if match:
            lead, middle, trail = match.groups()
            # Make URL we want to point to.
            url = None
            if middle.startswith('http://') or middle.startswith('https://'):
                url = urlquote(middle, safe='/&=:;#?+*')
            elif middle.startswith('www.') or ('@' not in middle and \
                    middle and middle[0] in string.ascii_letters + string.digits and \
                    (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
                url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
            elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
                url = 'mailto:%s' % middle
                nofollow_attr = ''
            # Make link.
            if url:
                trimmed = trim_url(middle)
                if autoescape and not safe_input:
                    lead, trail = escape(lead), escape(trail)
                    url, trimmed = escape(url), escape(trimmed)
                middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed)
                words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
            else:
                if safe_input:
                    words[i] = mark_safe(word)
                elif autoescape:
                    words[i] = escape(word)
        elif safe_input:
            words[i] = mark_safe(word)
        elif autoescape:
            words[i] = escape(word)
    return u''.join(words)
Esempio n. 2
0
    def render(self, name, value):
        if not self.attachments or not self.attachments.count():
            return ""

        output = []
        for doc in self.attachments:
            storage_info = doc["storage_info"]
            if not storage_info:
                thumb = ""
            elif storage_info.get("thumb_url", None):
                thumb = '<div class="thumb" style="background-image:url(\'%s\')"/>' % storage_info["thumb_url"]
            else:
                thumb = '<div class="no-thumb">%s</div>' % MIME_LABELS.get(doc["mime_type"], doc["mime_type"])

            output.append(
                '<li><a href="%(url)s">%(title)s %(thumb)s</a><br/><span><input type="checkbox" value="%(id)s" name="%(name)s"/>Remove</span></li>'
                % {
                    "url": storage_info["download_url"] if storage_info else "",
                    "title": doc["title"],
                    "thumb": thumb,
                    "id": doc["pk"],
                    "name": name,
                }
            )

        return mark_safe(u'<ul class="attachments">%s</ul>' % u"".join(output))
Esempio n. 3
0
 def get_content(self, lang='default'):
     regex = re.compile("\{(IMAGE|COLLECTION|ALL|FORM):(.*?)\}")
     content = page_get_content.send(instance=self, lang=lang, regex=regex)
     if not len(content) or not content[0]:
         content = mark_safe(regex.sub('', self['text']))
     else:
         content = content[0]
     return content
Esempio n. 4
0
 def get_content(self, lang='default'):
     regex = re.compile("\{(IMAGE|COLLECTION|ALL|FORM):(.*?)\}")
     content = page_get_content.send(instance=self, lang=lang, regex=regex)
     if not len(content) or not content[0]:
         content = mark_safe(regex.sub('', self['text']))
     else:
         content = content[0] 
     return content
Esempio n. 5
0
    def render(self, name, value, attrs=None):
        self.attrs = attrs or {}
        self.attrs['name'] = name
        self.attrs.setdefault('id', 'id_'+name)

        return mark_safe(u'<textarea %(attrs)s>%(value)s</textarea>'%{
                'attrs': ' '.join(['%s="%s"'%(k,v) for k,v in self.attrs.items()]),
                'value': value or '',
                })
Esempio n. 6
0
    def render(self, name, value, attrs=None):
        self.attrs = attrs or {}
        self.attrs['name'] = name
        self.attrs.setdefault('id', 'id_'+name)

        options = [u'<option value="%s"%s>%s</option>'%(k, self.get_selected(value, k), v)
                for k,v in self.choices]

        return mark_safe(u'<select %(attrs)s>%(options)s</select>'%{
                'attrs': ' '.join(['%s="%s"'%(k,v) for k,v in self.attrs.items()]),
                'options': ''.join(options),
                })
Esempio n. 7
0
 def clean(self, value):
     value = super(MarkdownField, self).clean(value)
     if not isinstance(value, basestring):
         raise ValidationError('Invalid type. Expected string: %s'%value)
     
     try:                
         value = markdown2.markdown(mark_safe(value))
     except:
         raise ValidationError('Error markdown: %s'%value)
         #value = ''
     else:
         return value or ''
Esempio n. 8
0
    def render(self, name, value, attrs=None):
        value = unicode(value or '')
        choices_dict = dict([(unicode(k), unicode(v)) for k,v in self.choices if k])
        attrs = attrs or {}
        attrs['autocomplete'] = 'off'

        if self.accept_not_found:
            attrs['class'] = attrs.get('class', '') + ' accept-not-found'

        ret = super(StaticAutoCompleteWidget, self).render('_'+name, choices_dict.get(value, value), attrs)
        options = '<ul class="static-auto-complete-options">%(options)s</ul>'%{
                'options': ''.join(['<li class="auto-complete-option" rel="%s"><a href="javascript:void(0)">%s</a></li>'%(k,v) for k,v in self.choices if k not in ('',None)]),
                }
        hidden = '<input type="hidden" name="%s" value="%s"/>'%(name, value or '')
        return mark_safe('<span class="static-auto-complete-container">%s %s %s</span>'%(ret, options, hidden))
Esempio n. 9
0
 def clean_value(self, inst, value):
     
     # Try to import markdonw2
     try:
         import markdown2
     except ImportError:
         markdown2 = None
         #raise ValidationError('Cannot import markdown2')
         
     if not isinstance(value, basestring):
         raise ValidationError('Invalid type. Expected string: %s'%value)
                 
     try:                
         value = markdown2.markdown(mark_safe(value))
     except:
         raise ValidationError('Error markdown: %s'%value)
     else:
         return value or ''
Esempio n. 10
0
    def render(self, name, value, attrs=None):
        attrs = attrs or {}
        if self.attrs:
            attrs.update(self.attrs)
        attrs['name'] = name
        
        # FIXME: maybe this should be moved with an opposite way to CheckboxInput
        if self.input_type != 'checkbox':
            attrs['value'] = self._format_value(value) if value is not None else ''
        
        attrs.setdefault('id', 'id_'+name)
        if self.readonly:
            attrs.setdefault('readonly', 'readonly')

        if self.input_type:
            attrs['type'] = self.input_type

        self.attrs.update(attrs) # XXX from the MERGE
        return mark_safe(u'<input %s/>'%' '.join(['%s="%s"'%(key,value) for key,value in attrs.items()]))
Esempio n. 11
0
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='', force_grouping=False):
    """
    Gets a number (as a number or string), and returns it as a string,
    using formats definied as arguments:

    * decimal_sep: Decimal separator symbol (for example ".")
    * decimal_pos: Number of decimal positions
    * grouping: Number of digits in every group limited by thousand separator
    * thousand_sep: Thousand separator symbol (for example ",")

    """
    use_grouping = force_grouping or settings.USE_L10N and \
        settings.USE_THOUSAND_SEPARATOR and grouping
    # Make the common case fast:
    if isinstance(number, int) and not use_grouping and not decimal_pos:
        return mark_safe(unicode(number))
    # sign
    if float(number) < 0:
        sign = '-'
    else:
        sign = ''
    str_number = unicode(number)
    if str_number[0] == '-':
        str_number = str_number[1:]
    # decimal part
    if '.' in str_number:
        int_part, dec_part = str_number.split('.')
        if decimal_pos is not None:
            dec_part = dec_part[:decimal_pos]
    else:
        int_part, dec_part = str_number, ''
    if decimal_pos is not None:
        dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
    if dec_part: dec_part = decimal_sep + dec_part
    # grouping
    if use_grouping:
        int_part_gd = ''
        for cnt, digit in enumerate(int_part[::-1]):
            if cnt and not cnt % grouping:
                int_part_gd += thousand_sep
            int_part_gd += digit
        int_part = int_part_gd[::-1]
    return sign + int_part + dec_part
Esempio n. 12
0
def localize(value, use_l10n=None):
    """
    Checks if value is a localizable type (date, number...) and returns it
    formatted as a string using current locale format.

    If use_l10n is provided and is not None, that will force the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    if isinstance(value, bool):
        return mark_safe(unicode(value))
    elif isinstance(value, (decimal.Decimal, float, int, long)):
        return number_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.datetime):
        return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
    elif isinstance(value, datetime.date):
        return date_format(value, use_l10n=use_l10n)
    elif isinstance(value, datetime.time):
        return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n)
    else:
        return value
    def render(self, page_number=None):
        page_number = page_number or self.request.GET.get('_page', 1)
        try:
            page_obj = self.page(page_number)
        except EmptyPage:
            raise Http404
        pages = get_page_range(self.page_range, page_number, self.pages_around_current)
        query_params = self.request.META.get('QUERY_STRING','').split('&')
        query_params = '&'.join([q for q in query_params if not q.startswith('_page')])

        html = render_to_string(
            'pagination/pagination.html',
            {
                'pages': pages,
                'page_obj': page_obj,
                'paginator': self,
                'is_paginated': self.count > self.per_page,
                'query_params': '&'+query_params,
                },
            )
        return mark_safe(html)
    def canonical_url_tag():
        protocol = 'https' if request.is_secure() else 'http'
        host = request.site['hostname'] if getattr(request, 'site', None) else request.META['HTTP_HOST']
        query_string = ('?'+request.META['QUERY_STRING']) if request.META.get('QUERY_STRING','') else ''
        current_url = '%s://%s%s%s'%(protocol, request.META['HTTP_HOST'], request.path_info, query_string)

        canonical_url = None
        if app_settings.CANONICAL_URL_FUNCTION:
            try:
                func = import_anything(app_settings.CANONICAL_URL_FUNCTION)
                canonical_url = func(request)
            except ImportError:
                pass

        if not canonical_url:
            canonical_url = '%s://%s%s%s'%(protocol, host, request.path_info, query_string)

        if current_url != canonical_url:
            return mark_safe('<link rel="canonical" href="%s"/>'%canonical_url)
        else:
            return ''
Esempio n. 15
0
    def render(self, name, value, attrs=None):
        self.attrs = attrs or {}
        self.attrs.setdefault('id', 'id_'+name)

        options = []
        for pk,display in self.choices:
            item_attrs = self.get_item_attrs(pk, display)
            options.append(
                u'<li><input type="checkbox" name="%(name)s[%(pk)s]" value="%(pk)s" id="%(id)s" %(sel)s %(attrs)s /> <label for="%(id)s">%(display)s</label></li>'%{
                    'name': name,
                    'pk': pk,
                    'id': 'id_%s_%s'%(name,pk),
                    'sel': self.get_selected(value, pk),
                    'display': display,
                    'attrs': ' '.join(['%s="%s"'%(k,v) for k,v in item_attrs.items()]),
                    })

        return mark_safe(u'<ul %(attrs)s>%(options)s</ul>'%{
                'attrs': ' '.join(['%s="%s"'%(k,v) for k,v in self.attrs.items()]),
                'options': ''.join(options),
                })
Esempio n. 16
0
    def render(self, name, value, attrs=None):
        substitutions = {
            'initial_text': self.initial_text,
            'input_text': self.input_text,
            'clear_template': '',
            'clear_checkbox_label': self.clear_checkbox_label,
        }
        template = u'%(input)s'
        substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)

        if value and hasattr(value, "url"):
            template = self.template_with_initial
            substitutions['initial'] = (u'<a href="%s" rel="nohistory">%s</a>'
                                        % (escape(value.url), escape(force_unicode(value))))
            if not self.is_required:
                checkbox_name = self.clear_checkbox_name(name)
                checkbox_id = self.clear_checkbox_id(checkbox_name)
                substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
                substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
                substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
                substitutions['clear_template'] = self.template_with_clear % substitutions

        return mark_safe(template % substitutions)
Esempio n. 17
0
    def render(self, name, value):
        if not self.attachments or not self.attachments.count():
            return ''

        output = []
        for doc in self.attachments:
            storage_info = doc['storage_info']
            if not storage_info:
                thumb = ''
            elif storage_info.get('thumb_url',None):
                thumb = '<div class="thumb" style="background-image:url(\'%s\')"/>' % storage_info['thumb_url']
            else:
                thumb = '<div class="no-thumb">%s</div>' % MIME_LABELS.get(doc['mime_type'],doc['mime_type'])

            output.append('<li><a href="%(url)s">%(title)s %(thumb)s</a><br/><span><input type="checkbox" value="%(id)s" name="%(name)s"/>Remove</span></li>' % {
                'url': storage_info['download_url'] if storage_info else '',
                'title': doc['title'],
                'thumb': thumb,
                'id': doc['pk'],
                'name': name,
                })

        return mark_safe(u'<ul class="attachments">%s</ul>' % u''.join(output))
Esempio n. 18
0
 def get_content(self):
     return mark_safe(self['body'])
Esempio n. 19
0
 def get_teaser(self):
     return mark_safe(self["teaser"])
Esempio n. 20
0
 def render(self, name, value, attrs=None):
     output = self.render_in_separate(name, value, attrs)
     return mark_safe(self.format_output(output))
Esempio n. 21
0
 def render(self):
     return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
Esempio n. 22
0
 def get_teaser(self):
     return mark_safe(self['teaser'])
Esempio n. 23
0
 def render_label(self, name, label):
     return mark_safe(u'<h2><span>%s</span></h2>' % name)
Esempio n. 24
0
def escape(html):
    """
    Returns the given HTML with ampersands, quotes and angle brackets encoded.
    """
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
Esempio n. 25
0
 def render_help_box(self, name, help_text):
     if not help_text:
         return ''
     return mark_safe(u'<span class="help_text" for="%s">%s</span>'%(self.attrs.get('id', name), help_text))
Esempio n. 26
0
 def render_errors(self, name, errors):
     if not errors:
         return ''
     return mark_safe(unicode(errors))
Esempio n. 27
0
 def render_label(self, name, label):
     return mark_safe(u'<label for="%s">%s:</label>'%(self.attrs.get('id', name), label))
Esempio n. 28
0
def escapejs(value):
    """Hex encodes characters for use in JavaScript strings."""
    for bad, good in _js_escapes:
        value = mark_safe(force_unicode(value).replace(bad, good))
    return value
Esempio n. 29
0
 def __unicode__(self):
     return u"Breadcrumbs <%s>" % u", ".join([mark_safe(item.name) for item in \
         self[:10]] + [u' ...'])
Esempio n. 30
0
 def get_content(self):
     return mark_safe(self["text"])
Esempio n. 31
0
 def get_full_path(self):
     return mark_safe(
         self.path_info + ("?" + self.META["QUERY_STRING"] if self.META.get("QUERY_STRING", None) else "")
     )
Esempio n. 32
0
 def render_label(self, name, label):
     return mark_safe(u'<h2><span>%s</span></h2>' % name)
Esempio n. 33
0
 def get_content(self):
     return mark_safe(self['text'])
 def __unicode__(self):
     return u"Breadcrumbs <%s>" % u", ".join([mark_safe(item.name) for item in \
         self[:10]] + [u' ...'])