Example #1
0
def header_for_result(result, headers):
    for i, td in enumerate(result):
        text = headers[i]['text']
        if not text.startswith('<'):
            yield mark_safe(td.replace('">', force_text('" data-label="%s : " >' % (text, ) )))
        else:
            yield mark_safe(td)
    def render(self, name, value, attrs=None):
        widget_attrs = self.build_widget_attrs(name)

        autocomplete = self.autocomplete(values=value)

        attrs = self.build_attrs(attrs, autocomplete=autocomplete)

        self.html_id = attrs.pop('id', name)

        choices = autocomplete.choices_for_values()
        values = [autocomplete.choice_value(c) for c in choices]

        context = {
            'name': name,
            'values': values,
            'choices': choices,
            'widget': self,
            'attrs': safestring.mark_safe(flatatt(attrs)),
            'widget_attrs': safestring.mark_safe(flatatt(widget_attrs)),
            'autocomplete': autocomplete,
        }
        context.update(self.extra_context)

        template = getattr(autocomplete, 'widget_template',
                self.widget_template)
        return safestring.mark_safe(render_to_string(template, context))
def add_class(value, css_class):
    """
    http://stackoverflow.com/questions/4124220/django-adding-css-classes-when-rendering-form-fields-in-a-template

    Inserts classes into template variables that contain HTML tags,
    useful for modifying forms without needing to change the Form objects.

    Usage:

        {{ field.label_tag|add_class:"control-label" }}

    In the case of REST Framework, the filter is used to add Bootstrap-specific
    classes to the forms.
    """
    html = six.text_type(value)
    match = class_re.search(html)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class,
                                                    css_class, css_class),
                      match.group(1))
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class,
                                          html))
    else:
        return mark_safe(html.replace('>', ' class="%s">' % css_class, 1))
    return value
Example #4
0
def static_content(content, render_mode):
    if render_mode == 'markdown':
        return mark_safe(markdown.markdown(unicode(content), ["settingsparser"]))
    elif render_mode == "html":
        return mark_safe(unicode(content))
    else:
        return unicode(content)
Example #5
0
 def get_page_number(self, i):
     if i == DOT:
         return mark_safe(u'<span class="dot-page">...</span> ')
     elif i == self.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(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1))
Example #6
0
def get_query_string(p_list, p_dict, new_params, remove, context):
    """
    Add and remove query parameters. From `django.contrib.admin`.
    """
    for r in remove:
        p_list = [[x[0], x[1]] for x in p_list if not x[0].startswith(r)]
    for k, v in new_params.items():
        if k in p_dict and v is None:
            p_list = [[x[0], x[1]] for x in p_list if not x[0] == k]
        elif k in p_dict and v is not None:
            for i in range(0, len(p_list)):
                if p_list[i][0] == k:
                    p_list[i][1] = [v]

        elif v is not None:
            p_list.append([k, [v]])

    for i in range(0, len(p_list)):
        if len(p_list[i][1]) == 1:
            p_list[i][1] = p_list[i][1][0]
        else:
            p_list[i][1] = mark_safe('&amp;'.join([u'%s=%s' % (p_list[i][0], k) for k in p_list[i][1]]))
            p_list[i][0] = ''

        protected_keywords = ['block']
        if p_list[i][1] not in protected_keywords:
            try:
                p_list[i][1] = template.Variable(p_list[i][1]).resolve(context)
            except:
                pass

    return mark_safe('?' + '&amp;'.join([k[1] if k[0] == '' else u'%s=%s' % (k[0], k[1]) for k in p_list if k[1] is not None and k[1] != 'None']).replace(' ', '%20'))
Example #7
0
 def as_text(self):
     """
     Dialog Forms rendered as summary just display their values instead of input fields.
     This is useful to render a summary of a previously filled out form.
     """
     try:
         return mark_safe(self.instance.as_text())
     except (AttributeError, TypeError):
         output = []
         for name in self.fields.keys():
             bound_field = self[name]
             value = bound_field.value()
             if bound_field.is_hidden:
                 continue
             if isinstance(value, (list, tuple)):
                 line = []
                 cast_to = type(tuple(bound_field.field.choices)[0][0])
                 for v in value:
                     try:
                         line.append(dict(bound_field.field.choices)[cast_to(v)])
                     except (AttributeError, KeyError):
                         pass
                 output.append(force_text(', '.join(line)))
             elif value:
                 try:
                     value = dict(bound_field.field.choices)[value]
                 except (AttributeError, KeyError):
                     pass
                 output.append(force_text(value))
         return mark_safe('\n'.join(output))
Example #8
0
    def render(self, name, value, attrs=None):

        value = value or ''
        
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        context = {
            'current_repr': mark_safe("'%s'" % escapejs(value)),
            'current_id': value,
            'help_text': self.help_text,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': reverse('ajax_lookup', args=[self.channel]),
            'name': name,
            'extra_attrs':mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #9
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            display = lookup.format_item_display(obj)
            current_repr = mark_safe( """new Array("%s",%s)""" % (escapejs(display),obj.pk) )
        else:
            current_repr = 'null'

        context = {
                'name': name,
                'html_id' : self.html_id,
                'min_length': getattr(lookup, 'min_length', 1),
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_repr': current_repr,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                }
        context.update(bootstrap())
        
        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #10
0
def candidate_office(c):
  """
  Usage:
  """
  ret = []

  state = c.state
  level = c.level
  office = c.office
  district = c.district

  try:
      if level == 'Federal':
          ret.append(office)
          ret.append(district)
      elif level == 'State':
          if office in ('Governor', 'Lt. Governor', 'Secretary of State'):
              ret.append(office)
          else:
              ret.append(level)
              ret.append(office)
              ret.append(district)
      elif level in Candidate.LEVEL_LIST:
          ret.append(office)
          ret.append(district)
      if not ret:
          log.error('Candidate %s: %s, %s, %s, %s', c, state, level, office,
                  district)
          ret.append('Unknown')
  except:
      raise
      log.error('Unknown error')
      pass

  return format_html('{} {}', mark_safe(state), mark_safe(' '.join(ret)))
Example #11
0
def group_message_details(request, group_id, message_id):
    group = get_object_or_404(GroupedMessage, pk=group_id)

    message = get_object_or_404(group.message_set, pk=message_id)
    
    if '__sentry__' in message.data and 'exc' in message.data['__sentry__']:
        module, args, frames = message.data['__sentry__']['exc']
        message.class_name = str(message.class_name)
        # We fake the exception class due to many issues with imports/builtins/etc
        exc_type = type(message.class_name, (Exception,), {})
        exc_value = exc_type(message.message)

        exc_value.args = args
    
        reporter = ImprovedExceptionReporter(message.request, exc_type, exc_value, frames, message.data['__sentry__'].get('template'))
        traceback = mark_safe(reporter.get_traceback_html())
    elif group.traceback:
        traceback = mark_safe('<pre>%s</pre>' % (group.traceback,))
    
    def iter_data(obj):
        for k, v in obj.data.iteritems():
            if k.startswith('_') or k in ['url']:
                continue
            yield k, v

    json_data = iter_data(message)

    page = 'messages'

    return render_to_response('sentry/group/message.html', locals(),
                              context_instance=RequestContext(request))
Example #12
0
def render_fatpage(request, f):
    """
    Internal interface to the fat 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 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 fatpage 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, {
        'fatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FatPage, f.id)
    return response
Example #13
0
    def form_valid(self, form):
        ticketed_event = form.save()
        messages.success(
            self.request, mark_safe('Event <strong> {}</strong> has been '
                                    'created!'.format(ticketed_event.name))
        )
        ActivityLog.objects.create(
            log='Ticketed Event {} (id {}) created by admin user {}'.format(
                ticketed_event, ticketed_event.id, self.request.user.username
            )
        )

        if ticketed_event.paypal_email != settings.DEFAULT_PAYPAL_EMAIL:
            messages.warning(
                self.request,
                mark_safe(
                    "You have changed the paypal receiver email from the "
                    "default value. If you haven't used this email before, "
                    "it is strongly recommended that you test the email "
                    "address "
                    "<a href='/studioadmin/test-paypal-email?email={}'>"
                    "here</a>".format(ticketed_event.paypal_email)
                )
            )

        return HttpResponseRedirect(self.get_success_url())
Example #14
0
def chain_recursion(r_id, store, id_dict):
    """Helper function for recusion"""
    
    i = pki.models.CertificateAuthority.objects.get(pk=r_id)
    
    div_content = build_delete_item(i)
    store.append( mark_safe('Certificate Authority: <a href="%s">%s</a> <img src="%spki/img/plus.png" class="switch" /><div class="details">%s</div>' % \
                            (urlresolvers.reverse('admin:pki_certificateauthority_change', args=(i.pk,)), i.name, MEDIA_URL, div_content)) )
    
    id_dict['ca'].append(i.pk)
    
    ## Search for child certificates
    child_certs = pki.models.Certificate.objects.filter(parent=r_id)
    if child_certs:
        helper = []
        for cert in child_certs:
            div_content = build_delete_item(cert)
            helper.append( mark_safe('Certificate: <a href="%s">%s</a> <img src="%spki/img/plus.png" class="switch" /><div class="details">%s</div>' % \
                                     (urlresolvers.reverse('admin:pki_certificate_change', args=(cert.pk,)), cert.name, MEDIA_URL, div_content)) )
            id_dict['cert'].append(cert.pk)
        store.append(helper)
    
    ## Search for related CA's
    child_cas = pki.models.CertificateAuthority.objects.filter(parent=r_id)
    if child_cas:
        helper = []
        for ca in child_cas:
            chain_recursion(ca.pk, helper, id_dict)
        store.append(helper)
Example #15
0
def embedly(url, size='640x480'):
    """ A very minimalistic implementation of embedly oembed content """

    size_match = re.match(r'^(?P<width>\d+)x(?P<height>\d+)$', size)

    if not size_match:
        raise Exception('Could not parse size, should be <width>x<height>')

    maxsizes = size_match.groupdict()

    params = {
        'url': url,
        'maxwidth': maxsizes['width'],
        'maxheight': maxsizes['height']
    }

    embedly_url = 'http://api.embed.ly/1/oembed?%s' % urlencode(params)
    cache_key = 'embedly_%s' % sha1(embedly_url).hexdigest()

    result = cache.get(cache_key)

    if not result:
        try:
            request = urllib2.urlopen(embedly_url)
            response = request.read()
            data = json.loads(response)
            result = mark_safe(data['html'])
            cache.set(cache_key, result)
        except urllib2.URLError:
            return mark_safe('<p>External content could not be loaded...</p>')

    return result
Example #16
0
def motion_details(request, days=3):
    devices = Device.objects.all()

    minutes = 10

    start = timezone.now() - timezone.timedelta(days=days)
    motion_time = []
    motion_count = []
    delta = timezone.timedelta(minutes=minutes)

    while start < timezone.now():
        cnt = Log.objects.filter(log_type__exact='MO', status=True, created__range=[start, start+delta]).count()
        motion_time.append(start)
        motion_count.append(cnt)

        start += delta
#    motion_datestmp = last_motion
    motion_time = mark_safe([timezone.localtime(m).strftime('%Y-%m-%d %H:%M:%S') for m in motion_time].__str__())
    #motion_state = mark_safe([ int(m.status) for m in last_motions].__str__())
    #motion_time = mark_safe(motion_time.__str__())
    motion_count = mark_safe(motion_count.__str__())

    range_start = mark_safe(timezone.localtime(timezone.now()-timezone.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
    range_end = mark_safe(timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S'))

    return render_to_response(
        'motions.html',
        locals()
    )
def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        name = six.text_type(value.obj)
        return mark_safe('<a href=%s>%s</a>' % (value, escape(name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template('rest_framework/admin/list_value.html')
        else:
            template = loader.get_template('rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, six.string_types):
        if (
            (value.startswith('http:') or value.startswith('https:')) and not
            re.search(r'\s', value)
        ):
            return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value)
Example #18
0
def render_os(os):
    try:
        t, flavor = os.split("+", 1)
        flavor = " ".join(i.capitalize() for i in flavor.split("-"))
        return mark_safe("%s (<em>%s</em>)" % (flavor, t))
    except ValueError:
        return mark_safe(_("<em>Unknown or invalid OS</em>"))
    def _fetch_womi_params(self, request, womi_id, version):
        if version == 'none' or not self.use_version:
            version = None

        # TODO better way to obtain this path?
        womi_url = '/content/womi/%s/' % womi_id
        if self.use_version:
            womi_url += ('%s/' % version)

        full_domain = self.get_full_domain()
        with_schema_base_url = ('https:' if request.is_secure() else 'http:') + full_domain
        data = {'womi_url': womi_url,
                'base_url': with_schema_base_url}

        if self.use_dynamic:
            womi_content = mark_safe(self.get_dynamic_loader(womi_id, version))
        else:
            try:
                manifest_url = 'http:' + full_domain + womi_url + 'manifest.json'
                debug('fetching manifest %s', manifest_url)
                r = requests.get(manifest_url)
                r.raise_for_status()
                data.update(r.json())
                womi_content = resolve_womi(data)
            except ConnectionError as ce:
                womi_content = mark_safe(self.get_dynamic_loader(womi_id, version))

        return {
            'base_url': full_domain,
            'womi_id': womi_id,
            'version': version,
            'data': data,
            'womi_content': womi_content,
            'endpoints': self.endpoints
        }
Example #20
0
    def test_reporting_of_nested_exceptions(self):
        request = self.rf.get('/test_view/')
        try:
            try:
                raise AttributeError(mark_safe('<p>Top level</p>'))
            except AttributeError as explicit:
                try:
                    raise ValueError(mark_safe('<p>Second exception</p>')) from explicit
                except ValueError:
                    raise IndexError(mark_safe('<p>Final exception</p>'))
        except Exception:
            # Custom exception handler, just pass it into ExceptionReporter
            exc_type, exc_value, tb = sys.exc_info()

        explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:'
        implicit_exc = 'During handling of the above exception ({0}), another exception occurred:'

        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        # Both messages are twice on page -- one rendered as html,
        # one as plain text (for pastebin)
        self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;')))
        self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;')))
        self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;'))

        text = reporter.get_traceback_text()
        self.assertIn(explicit_exc.format('<p>Top level</p>'), text)
        self.assertIn(implicit_exc.format('<p>Second exception</p>'), text)
        self.assertEqual(3, text.count('<p>Final exception</p>'))
def paginator_prev_page(cl):
    prevpage= cl.page_num -1 
    if prevpage <= -1:
        prevpage=0
        return mark_safe(u'<li class="active"><span>Prev</span></li>' )
    else:
        return mark_safe(u'<li><a href="%s">Prev</a></li> ' % (escape(cl.get_query_string({PAGE_VAR: prevpage}))))
Example #22
0
def project_div(project):
    d = dict(name=esc(project.name), color=esc(project.color))
    if project.display_as_free:
        return mark_safe('<div class="project %(color)s"></div>' % d)
    else:
        d['url'] = project.get_absolute_url()
        return mark_safe('<a href="%(url)s" class="project %(color)s" title="%(name)s"></a>' % d)
Example #23
0
def get_image_tags_per_issue(issue, alt_text, zoom_level, as_list=False,
                             variants=False, exclude_ids=None):
    if issue.has_covers() or (variants and issue.variant_covers().count()):
        covers = issue.active_covers()
        if variants:
            covers = covers | issue.variant_covers()
    else:
        return mark_safe(get_image_tag(cover=None, zoom_level=zoom_level,
                    alt_text=alt_text,
                    can_have_cover=issue.can_have_cover()))

    if exclude_ids:
        covers = covers.exclude(id__in=exclude_ids)
    if as_list:
        cover_tags = []
        alt_string = u'Cover for %s' % issue.full_name()
    else:
        tag = ''

    for cover in covers:
        if as_list:
            active = cover.revisions.filter(changeset__state__in=states.ACTIVE)
            cover_tags.append([cover, issue,
                               get_image_tag(cover, alt_string, zoom_level),
                               active.count()])
        else:
            tag += get_image_tag(cover=cover, zoom_level=zoom_level,
                                 alt_text=alt_text)
    if as_list:
        return cover_tags
    else:
        return mark_safe(tag)
Example #24
0
    def render_buglinks(self, record, table=None):

        suite_links_count = BugLink.objects.filter(
            content_type=ContentType.objects.get_for_model(TestSuite),
            object_id=record.id).count()
        case_links_count = BugLink.objects.filter(
            content_type=ContentType.objects.get_for_model(TestCase),
            object_id__in=TestCase.objects.filter(
                suite=record)).count()

        user = table.context.get('request').user
        if not user.is_anonymous():
            return mark_safe(
                '<a href="#" class="buglink" id="buglink_%s">[%s]</a> (%s)' % (
                    record.id,
                    suite_links_count,
                    case_links_count
                )
            )
        else:
            return mark_safe(
                '[%s] (%s)' % (
                    suite_links_count,
                    case_links_count
                )
            )
Example #25
0
def paginator_number(cl,i):
    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> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1))
Example #26
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs,  name=name)
        self.html_id = final_attrs.pop('pk', name)

        lookup = get_lookup(self.channel)
        if value:
            current_result = mark_safe(lookup.format_result( lookup.get_objects([value])[0] ))
        else:
            current_result = ''

        context = {
                'name': name,
                'html_id' : self.html_id,
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_result': current_result,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                'admin_media_prefix' : settings.ADMIN_MEDIA_PREFIX
                }

        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #27
0
    def get(self, request, *args, **kwargs):

        if not self.has_permission(request):
            return self.handle_permission_denied(request)

        template_name = rfs.SWAGGER_SETTINGS.get('template_path')
        data = {
            'swagger_settings': {
                'discovery_url': "%s/api-docs/" % get_full_base_path(request),
                'api_key': rfs.SWAGGER_SETTINGS.get('api_key', ''),
                'api_version': rfs.SWAGGER_SETTINGS.get('api_version', ''),
                'token_type': rfs.SWAGGER_SETTINGS.get('token_type'),
                'enabled_methods': mark_safe(
                    json.dumps(rfs.SWAGGER_SETTINGS.get('enabled_methods'))),
                'doc_expansion': rfs.SWAGGER_SETTINGS.get('doc_expansion', ''),
            },
            'rest_framework_settings': {
                'DEFAULT_VERSIONING_CLASS':
                    settings.REST_FRAMEWORK.get('DEFAULT_VERSIONING_CLASS', '')
                    if hasattr(settings, 'REST_FRAMEWORK') else None,

            },
            'django_settings': {
                'CSRF_COOKIE_NAME': mark_safe(
                    json.dumps(getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'))),
            }
        }
        response = render_to_response(
            template_name, RequestContext(request, data))

        return response
Example #28
0
    def test_mark_safe_lazy(self):
        s = lazystr('a&b')
        b = lazybytes(b'a&b')

        self.assertIsInstance(mark_safe(s), SafeData)
        self.assertIsInstance(mark_safe(b), SafeData)
        self.assertRenderEqual('{{ s }}', 'a&b', s=mark_safe(s))
Example #29
0
    def prepare(self):
        # Set the template and title for the page content, if they are not set (but don't save them)
        self.title = self.title or self.page.title
        self.template = self.template or self.page.template
        self.slug = self.slug or self.page.slug

        if not self.description:
            self.description = ''
        if not self.keywords:
            self.keywords = ''
        if not self.page_topic:
            self.page_topic = ''
    
        # Convert the content to HTML
        if self.content_type == 'html':
            pass # Nothing to do
        elif self.content_type == 'markdown':
            self.content = markdown(self.content)
        elif self.content_type == 'textile':
            self.content = textile(self.content)
        elif self.content_type == 'rst':
            self.content = rst(self.content)
        else:
            self.content = mark_safe(linebreaks(escape(self.content)))
        self.toc = mark_safe(self.toc)
        return self
Example #30
0
 def get_render_content(self, context):
     if self.nodelist:
         with context.push():
             context['content'] = self.get_content_from_context(context)
             output = self.nodelist.render(context)
         return mark_safe(output)
     return mark_safe(self.get_content_from_context(context))
Example #31
0
class SubscriptionForm(PluginSettingsFormMixin, forms.Form):

    settings_form_headline = _('Notifications')
    settings_order = 1
    settings_write_access = False

    settings = SettingsModelChoiceField(None,
                                        empty_label=None,
                                        label=_('Settings'))
    edit = forms.BooleanField(required=False,
                              label=_('When this article is edited'))
    edit_email = forms.BooleanField(
        required=False,
        label=_('Also receive emails about article edits'),
        widget=forms.CheckboxInput(
            attrs={
                'onclick':
                mark_safe(
                    "$('#id_edit').attr('checked', $(this).is(':checked'));")
            }))

    def __init__(self, article, request, *args, **kwargs):

        self.article = article
        self.user = request.user
        initial = kwargs.pop('initial', None)
        self.notification_type = NotificationType.objects.get_or_create(
            key=ARTICLE_EDIT,
            content_type=ContentType.objects.get_for_model(article))[0]
        self.edit_notifications = models.ArticleSubscription.objects.filter(
            article=article,
            subscription__notification_type=self.notification_type,
            subscription__settings__user=self.user,
        )
        self.default_settings = Settings.get_default_setting(request.user)
        if self.edit_notifications:
            self.default_settings = self.edit_notifications[
                0].subscription.settings
        if not initial:
            initial = {
                'edit':
                bool(self.edit_notifications),
                'edit_email':
                bool(
                    self.edit_notifications.filter(
                        subscription__send_emails=True)),
                'settings':
                self.default_settings,
            }
        kwargs['initial'] = initial
        super().__init__(*args, **kwargs)
        self.fields['settings'].queryset = Settings.objects.filter(
            user=request.user, )

    def get_usermessage(self):
        if self.changed_data:
            return _('Your notification settings were updated.')
        else:
            return _(
                'Your notification settings were unchanged, so nothing saved.')

    def save(self, *args, **kwargs):

        cd = self.cleaned_data
        if not self.changed_data:
            return
        if cd['edit']:
            try:
                edit_notification = models.ArticleSubscription.objects.get(
                    subscription__notification_type=self.notification_type,
                    article=self.article,
                    subscription__settings=cd['settings'],
                )
                edit_notification.subscription.send_emails = cd['edit_email']
                edit_notification.subscription.save()
            except models.ArticleSubscription.DoesNotExist:
                subscription, __ = Subscription.objects.get_or_create(
                    settings=cd['settings'],
                    notification_type=self.notification_type,
                    object_id=self.article.id,
                )
                edit_notification = models.ArticleSubscription.objects.create(
                    subscription=subscription,
                    article=self.article,
                )
                subscription.send_emails = cd['edit_email']
                subscription.save()

        else:
            self.edit_notifications.delete()
Example #32
0
def md(event, fieldName=None):
    if fieldName is None:
        if event.typeName == 'document' or event.typeName == 'minutes':
            itemtype = 'http://schema.org/Article'
            itemtypeclass = 'documenttype'
        else:
            itemtype = 'http://schema.org/Event'
            itemtypeclass = 'eventtype'
        return mark_safe('''<div '''
                         '''id="%s-%s" '''
                         '''class="%s editthis" '''
                         '''itemscope '''
                         '''itemtype="%s" '''
                         '''data-modeltype="%s" '''
                         '''data-modelid="%s" '''
                         '''data-apiobjecturl="%s">''' % (
                             event.typeName.lower(),
                             event.id,
                             itemtypeclass,
                             itemtype,
                             event.typeName,
                             event.id,
                             event.api_object_url,
                         ))
    else:
        if MDPROPS[fieldName] == '':
            itemprop = ''
        else:
            itemprop = ' itemprop="%s"' % MDPROPS[fieldName]
            # return '<span itemprop="name" data-bind="text:title">{{ maintitle|title }}</span>'
        # elif fieldName == 'festivals':
        # festivals = []
        #     for festival in event.festival_set.all():
        #         festivals.append(
        #             '''<h3 itemprop="superEvent" itemscope itemtype="http://schema.org/Event">'''
        #             '''Part of <a itemprop="url" href="%s"><span itemprop="name">%s</span></a>'''
        #             '''</h3>''' % (
        #                 festival.get_absolute_url(),
        #                 festival,
        #             ))
        #     return mark_safe(''.join(festivals))
        if fieldName == 'startDate':
            return mark_safe(
                '''<time class="%s"%s datetime="%s" data-bind="attr:{datetime:startDateTime()},text:displayStart()">%s</time>'''
                % (
                    fieldName,
                    itemprop,
                    event.startDate,
                    event.displayStart,
                ))
        elif fieldName == 'startDateTime':
            return mark_safe(
                '''<time class="%s"%s datetime="%s" data-bind="attr:{datetime:startDateTime()},text:displayStart()">%s</time>'''
                % (
                    fieldName,
                    itemprop,
                    event.startDateTime,
                    event.displayStart,
                ))
        elif fieldName == 'endDateTime':
            return mark_safe(
                '''<time class="%s"%s datetime="%s" data-bind="attr:{datetime:endDateTime()},text:displayEnd()">%s</time>'''
                % (
                    fieldName,
                    itemprop,
                    event.endDateTime,
                    event.displayEnd,
                ))
        elif fieldName == 'endDate':
            return mark_safe(
                '''<time class="%s"%s datetime="%s" data-bind="attr:{datetime:endDateTime()},text:displayEnd()">%s</time>'''
                % (
                    fieldName,
                    itemprop,
                    event.endDate,
                    event.displayEnd,
                ))
        elif fieldName == 'length':
            return mark_safe(
                '''<time class="%s"%s datetime="%s" data-bind="attr:{datetime:isolength()},text:lengthLabel()">%s</time>'''
                % (
                    fieldName,
                    itemprop,
                    event.isolength,
                    event.length,
                ))
        elif fieldName == 'summary':
            return ''
        elif fieldName == 'body' or fieldName == 'articleBody':
            return mark_safe(
                '''<div class="%s"%s data-fieldname="body" data-bind="htmlValue:body">%s</div>'''
                % (
                    fieldName,
                    itemprop,
                    #event.body,
                    sanitize(event.body),
                ))
        elif fieldName == 'director':
            return mark_safe(
                '''<span itemprop="%s" itemscope itemtype="http://schema.org/Person"><span class="%s"%s data-bind="text:%s">%s</span></span>'''
                % (
                    fieldName,
                    fieldName,
                    itemprop,
                    fieldName,
                    getattr(event, fieldName),
                ))
        elif fieldName == 'year':
            if event.year:
                yearb = '(%s)' % event.year
            else:
                yearb = ''
            return mark_safe(
                '''<span class="%s"%s content="%s" data-bind="attr:{content:year}, text: showYear()"> %s</span>'''
                % (fieldName, itemprop, event.year, yearb))
        elif fieldName == 'certificate' or fieldName == 'filmFormat' or fieldName == 'approval' or fieldName == 'programmer':
            return mark_safe(
                '''<span class="%s"%s data-bind="text:%s">%s</span>''' % (
                    fieldName,
                    itemprop,
                    'selectedLabel' + fieldName,
                    getattr(event, fieldName),
                ))
        elif fieldName == 'season':
            season = getattr(event, fieldName)
            if season is None:
                season = Season.objects.get(id=2)
            if season.id == 2:
                visibility = ''' style="display: none;"'''
            else:
                visibility = ''
            return mark_safe(
                '''<h3%s data-bind="visible: %s()">Part of the <a href="%s" class="%s"%s data-bind="attr:{href:%s},text:%s">%s</a></h3>'''
                % (
                    visibility,
                    'selectedVisible' + fieldName,
                    season.get_absolute_url(),
                    fieldName,
                    itemprop + ' itemscope itemtype="http://schema.org/Event"',
                    'selectedLink' + fieldName,
                    'selectedLabel' + fieldName,
                    season,
                ))
        elif fieldName == 'meeting':
            return mark_safe(
                '''Minutes of <a href="%s" class="%s"%s data-bind="attr:{href:%s},text:%s">%s</a>'''
                % (
                    getattr(event, fieldName).get_absolute_url(),
                    fieldName,
                    itemprop + ' itemscope itemtype="http://schema.org/Event"',
                    'selectedLink' + fieldName,
                    'selectedLabel' + fieldName,
                    event.meeting.longHeading,
                ))
        elif fieldName == 'picture':
            if event.picture is None:
                event.picture = Picture.objects.get(id=789)
            try:
                displaySrc = event.picture.displaySrc
            except (IOError, IndexError):
                event.picture = Picture.objects.get(id=1960)
                displaySrc = event.picture.displaySrc
            return mark_safe(
                '''<img class="%s pull-right img-responsive"%s'''
                ''' data-fieldname="picture"'''
                ''' src="%s"'''
                ''' width="%s"'''
                ''' height="%s"'''
                ''' data-src="%s"'''
                ''' data-width="%s"'''
                ''' data-height="%s"'''
                ''' data-toggle="modal"'''
                ''' data-target="#img-picture-%s"'''
                ''' alt=""'''
                ''' data-bind="attr: {'''
                ''' src: pictureData().displaySrc,'''
                ''' width: pictureData().displayWidth,'''
                ''' height: pictureData().displayHeight,'''
                ''' 'data-src': pictureData().src,'''
                ''' 'data-width': pictureData().width,'''
                ''' 'data-height': pictureData().height'''
                ''' }" />'''
                '''<div class="modal " id="img-picture-%s">'''
                '''    <div class="modal-dialog">'''
                '''        <div class="modal-content">'''
                '''            <div class="modal-header">'''
                '''                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">'''
                '''                    &times;'''
                '''                </button>'''
                '''            </div>'''
                '''            <div class="modal-body">'''
                '''                <img src="%s" class="img-responsive" alt="" data-bind="attr: {src: pictureData().displaySrc}">'''
                '''            </div>'''
                '''        </div>'''
                '''    </div>'''
                '''</div>''' % (
                    fieldName,
                    itemprop,
                    displaySrc,
                    event.picture.displayWidth,
                    event.picture.displayHeight,
                    event.picture.src,
                    event.picture.width,
                    event.picture.height,
                    event.picture.id,
                    event.picture.id,
                    event.picture.src,
                ))
        # elif fieldName == 'notes':
        # elif fieldName == 'approval':
        # elif fieldName == 'confirmed':
        # elif fieldName == 'private':
        # elif fieldName == 'featured':
        elif fieldName == 'website':
            if str(event.website) == '':
                label_text = ''
            else:
                label_text = 'External Website: '
            return mark_safe(
                '''<div itemprop="subEvents" itemscope itemtype="http://schema.org/Event" data-bind="visible:websiteVisible">'''
                '''    <meta itemprop="name" content="%s">'''
                '''    <p>%s<a itemprop="url" data-bind="attr:{href:website},text:website" href="%s">%s</a></p>'''
                '''</div>''' % (
                    event.title,
                    label_text,
                    event.website,
                    event.website,
                ))
        # elif fieldName == 'films':
        # elif fieldName == 'gigs':
        # elif fieldName == 'events':
        elif fieldName == 'festivals':
            return ''
        else:
            try:
                return mark_safe(
                    '''<span class="%s"%s data-bind="text:%s">%s</span>''' % (
                        fieldName,
                        itemprop,
                        fieldName,
                        getattr(event, fieldName),
                    ))
            except AttributeError:
                return mark_safe('''<span>Error</span>''')
Example #33
0
def sanitize(value):
    parenty = re.compile(r'"(\.\.\/)+', re.MULTILINE | re.IGNORECASE)
    value = parenty.sub(r'"/', value)
    # oldstyle = re.compile(r'<b>(.*?)</b>', re.MULTILINE | re.IGNORECASE)
    #value = oldstyle.sub(r'<strong>\1</strong>', value)
    #oldstyle = re.compile(r'<i>(.*?)</i>', re.MULTILINE | re.IGNORECASE)
    #value = oldstyle.sub(r'<em>\1</em>', value)
    styletag = re.compile(r'<style(.*?)</style>', re.MULTILINE | re.IGNORECASE)
    value = styletag.sub(r'', value)
    tags = [
        'div',
        'span',
        'p',
        'h1',
        'h2',
        'h3',
        'h4',
        'h5',
        'h6',
        'ul',
        'ol',
        'li',
        'dl',
        'dt',
        'dd',
        'a',
        'strong',
        'b',
        'em',
        'i',
        'hr',
        'abbr',
        'acronym',
        'blockquote',
        'code',
        'img',
        'iframe',
    ]
    attributes = {
        '*': [
            'class',
        ],
        'a': [
            'href',
            'title',
        ],
        'abbr': [
            'title',
        ],
        'acronym': [
            'title',
        ],
        'img': ['height', 'width', 'alt', 'title', 'src'],
        'iframe': ['height', 'width', 'src', 'frameborder', 'allowfullscreen'],
    }
    value = bleach.clean(value, tags=tags, attributes=attributes, strip=True)
    #value = bleach.linkify(value, nofollow=False) # this breaks youtube iframes, which is a shame.
    soup = BeautifulSoup(value)
    for img in soup.findAll('img'):
        try:
            if img['src'][0] != '/':
                urlelements = img['src'].split('/')
                if urlelements[2] == 'www.starandshadow.org.uk' or urlelements[
                        2] == '127.0.0.1:8000':
                    img['src'] = img['src'].split(urlelements[2])[1]
                else:
                    img['src'] = '/static/img/import/%s?origsrc=%s' % (
                        img['src'].split('/')[-1], img['src'])
        except KeyError:
            img.extract()
    for mso in soup.findAll(True, "MsoNormal"):
        del (mso['class'])
    for tag in soup.findAll(
            lambda tag: (tag.name == 'span' or tag.name == 'p' or tag.name ==
                         'div') and tag.find(True) is None and
        (tag.string is None or tag.string.strip() == '')):
        tag.extract()
    value = soup.renderContents().decode('utf8')
    dotty = re.compile(r'\.{2,}', re.MULTILINE | re.IGNORECASE)
    value = dotty.sub(r'&hellip;', value)
    liny = re.compile(r'[_-]{2,}', re.MULTILINE | re.IGNORECASE)
    value = liny.sub(r'<hr>', value)
    starry = re.compile(r'\*{1,}([^\*]*)\*{1,}', re.MULTILINE | re.IGNORECASE)
    value = starry.sub(r'<strong>\1</strong>', value)
    return mark_safe(value)
Example #34
0
def brick_display(context, *bricks, **kwargs):
    """ Display some Brick instances.

    Note: see {% brick_import %} & {% brick_declare %} on how to get Bricks
    instances in your context.

        {% load creme_bricks %}

        [...]

        {% brick_display my_brick1 my_brick2 %}

    By default, the method detailview_display() of the bricks is called ;
    but you can call the different render method by giving the keyword argument 'render':

        {% brick_display my_brick1 my_brick2 render='home' %}

    Possible values are:
       - 'detail'  => detailview_display() (default value)
       - 'home'    => home_display()
    """
    context_dict = context.flatten()
    render_type = kwargs.get('render', 'detail')

    try:
        brick_render_method = _DISPLAY_METHODS[render_type]
    except KeyError as e:
        raise ValueError(
            '{{% brick_display %}}: "render" argument must be in [{}].'.format(
                ', '.join(_DISPLAY_METHODS.keys())
            )
        ) from e

    def render(brick):
        fun = getattr(brick, brick_render_method, None)

        if fun:
            # NB: the context is copied is order to a 'fresh' one for each brick,
            #     & so avoid annoying side-effects.
            return fun({**context_dict})

        logger.warning(
            'Brick without %s(): %s (id=%s)',
            brick_render_method, brick.__class__, brick.id_,
        )

    bricks_to_render = []

    def pop_group(brick_id):
        try:
            BricksManager.get(context).pop_group(brick_id)
        except KeyError as e:
            raise ValueError(
                '{{% brick_display %}}: it seems that this brick has not been '
                f'declared/imported: {brick_id}'
            ) from e

    for brick_or_seq in bricks:
        if brick_or_seq == '':
            raise ValueError(
                '{% brick_display %}: "bricks" seems empty. Is you variable valid ?'
            )

        # We avoid generator, because we need to iterate twice (import & display)
        if isinstance(brick_or_seq, (list, tuple)):
            for brick in brick_or_seq:
                pop_group(brick.id_)
                bricks_to_render.append(brick)
        else:
            pop_group(brick_or_seq.id_)
            bricks_to_render.append(brick_or_seq)

    return mark_safe(''.join(filter(
        None,
        (render(brick) for brick in bricks_to_render)
    )))
Example #35
0
def brick_header_title(
        context, title, plural=None, empty=None, icon='info',
        count=None, selection_title=None, selection_plural=None):
    """Display the title of a brick.
    Should be used in the template block 'brick_header_title'.

    @param title: Title of the brick. If you want to display a number of items
           (eg: number of lines in this brick) & so pluralize the title, use a
           format variable '{count}' and the parameter 'plural'.
    @param plural: Title to use with a plural number of items. If you set it,
           it must use format variable '{count}' & the parameter 'title' too.
    @param empty: Title to use it there no items in the bricks.
    @param icon: The string identifying an Icon (eg: 'add'), or an Icon instance
           (see the templatetag {% widget_icon  %} of the lib creme_widget.
           Default is 'info' icon.
    @param count: Number of items in the bricks. If you don't set it, & the
           brick is paginated, the paginator's count is used.
    @param selection_title: Additional text displayed in title of bricks which
           allows to select items. The related brick must have the class
           'brick-selectable' & a column with class 'data-selectable-selector-column'.
           Must use a format variable '%s'.
           If set, the parameter 'selection_plural' must be set too.
    @param selection_plural: See 'selection_title'.

    Example 1 - basic text with info icon:
        {% extends 'creme_core/bricks/base/base.html' %}
        {% load i18n creme_bricks %}

        {% block brick_header_title %}
            {% brick_header_title title=_('Customers and providers') %}
        {% endblock %}

        ...

    Example 2 - paginated & named icon:
        {% extends 'creme_core/bricks/base/paginated-table.html' %}
        {% load i18n creme_bricks %}

        {% block brick_header_title %}
            {% brick_header_title
               title=_('{count} Customers') plural=_('{count} Customers')
               empty=_('Customers') icon='phone' %}
        {% endblock %}

        ...

    Example 3 - instanced icon (notice the size):
        {% extends 'creme_core/bricks/base/list.html' %}
        {% load i18n creme_bricks creme_widgets %}

        {% block brick_header_title %}
            {% widget_icon ctype=my_ct size='brick-header' as my_icon %}
            {% brick_header_title title=my_title icon=my_icon %}
        {% endblock %}

        ...
    """
    if count is None:
        count = context.get('page').paginator.count if 'page' in context else 0

    if count == 0:
        title_fmt = empty or title
    elif is_plural(count):
        title_fmt = plural or title
    else:
        title_fmt = title

    rendered_title = title_fmt.format(count=count)
    if isinstance(title_fmt, SafeData):
        rendered_title = mark_safe(rendered_title)

    if isinstance(icon, str):
        # TODO: cache ?
        theme = get_current_theme_from_context(context)
        icon = get_icon_by_name(
            icon, theme,
            size_px=get_icon_size_px(theme, size='brick-header'),
            label=_('Information') if icon == 'info' else rendered_title,
        )

    return {
        'title': rendered_title,
        'icon': icon,
        'selection_title': selection_title,
        'selection_plural': selection_plural,
    }
Example #36
0
def buyersumbonus(value):
    from node.models import discountcard
    data = discountcard.objects.filter(buyer__id=value).aggregate(
        s=Sum('bonus'))['s']
    return mark_safe(data)
Example #37
0
 def render(self):
     return mark_safe(self.template_string.format(
         self.context_key,
         self.get_content()))
Example #38
0
def markcode(value):
    return mark_safe(markdown.markdown(force_unicode(value),extensions=['codehilite']))
Example #39
0
 def get_markdown(self):
     content = self.content
     markdown_text = markdown(content)
     return mark_safe(markdown_text)
Example #40
0
def expected_bulk_app_sheet_rows(app):
    """
    Data rows for bulk app translation download
    """

    # keys are the names of sheets, values are lists of tuples representing rows
    rows = OrderedDict({MODULES_AND_FORMS_SHEET_NAME: []})

    for mod_index, module in enumerate(app.get_modules()):
        # This is duplicated logic from expected_bulk_app_sheet_headers,
        # which I don't love.
        module_string = "module" + str(mod_index + 1)

        # Add module to the first sheet
        row_data = _make_modules_and_forms_row(
            row_type="Module",
            sheet_name=module_string,
            languages=[module.name.get(lang) for lang in app.langs],
            media_image=[module.icon_by_language(lang) for lang in app.langs],
            media_audio=[module.audio_by_language(lang) for lang in app.langs],
            unique_id=module.unique_id,
        )
        rows[MODULES_AND_FORMS_SHEET_NAME].append(row_data)

        # Populate module sheet
        rows[module_string] = []
        if not isinstance(module, ReportModule):
            if module.case_list_form.form_id:
                # Add row for label of case list registration form
                rows[module_string].append(
                        ('case_list_form_label', 'list') +
                        tuple(module.case_list_form.label.get(lang, '') for lang in app.langs)
                )

            for list_or_detail, detail in [
                ("list", module.case_details.short),
                ("detail", module.case_details.long)
            ]:
                # Add a row for each tab heading
                for index, tab in enumerate(detail.tabs):
                    rows[module_string].append(
                        ("Tab {}".format(index), list_or_detail) +
                        tuple(tab.header.get(lang, "") for lang in app.langs)
                    )

                # Add a row for each detail field
                # Complex fields may get multiple rows
                case_properties = detail.get_columns()
                for detail in case_properties:

                    field_name = detail.field
                    if re.search(r'\benum\b', detail.format):   # enum, conditional-enum, enum-image
                        field_name += " (ID Mapping Text)"
                    elif detail.format == "graph":
                        field_name += " (graph)"

                    # Add a row for this case detail
                    rows[module_string].append(
                        (field_name, list_or_detail) +
                        tuple(detail.header.get(lang, "") for lang in app.langs)
                    )

                    # Add a row for any mapping pairs
                    if re.search(r'\benum\b', detail.format):
                        for mapping in detail.enum:
                            rows[module_string].append(
                                (
                                    mapping.key + " (ID Mapping Value)",
                                    list_or_detail
                                ) + tuple(
                                    mapping.value.get(lang, "")
                                    for lang in app.langs
                                )
                            )

                    # Add rows for graph configuration
                    if detail.format == "graph":
                        for key, val in six.iteritems(detail.graph_configuration.locale_specific_config):
                            rows[module_string].append(
                                (
                                    key + " (graph config)",
                                    list_or_detail
                                ) + tuple(val.get(lang, "") for lang in app.langs)
                            )
                        for i, series in enumerate(detail.graph_configuration.series):
                            for key, val in six.iteritems(series.locale_specific_config):
                                rows[module_string].append(
                                    (
                                        "{} {} (graph series config)".format(key, i),
                                        list_or_detail
                                    ) + tuple(val.get(lang, "") for lang in app.langs)
                                )
                        for i, annotation in enumerate(detail.graph_configuration.annotations):
                            rows[module_string].append(
                                (
                                    "graph annotation {}".format(i + 1),
                                    list_or_detail
                                ) + tuple(
                                    annotation.display_text.get(lang, "")
                                    for lang in app.langs
                                )
                            )

            for form_index, form in enumerate(module.get_forms()):
                form_string = module_string + "_form" + str(form_index + 1)
                xform = form.wrapped_xform()

                # Add row for this form to the first sheet
                # This next line is same logic as above :(
                first_sheet_row = _make_modules_and_forms_row(
                    row_type="Form",
                    sheet_name=form_string,
                    languages=[form.name.get(lang) for lang in app.langs],
                    # leave all
                    media_image=[form.icon_by_language(lang) for lang in app.langs],
                    media_audio=[form.audio_by_language(lang) for lang in app.langs],
                    unique_id=form.unique_id
                )

                # Add form to the first street
                rows[MODULES_AND_FORMS_SHEET_NAME].append(first_sheet_row)

                if form.form_type == 'shadow_form':
                    continue

                # Populate form sheet
                rows[form_string] = []

                itext_items = OrderedDict()
                try:
                    nodes = xform.itext_node.findall("./{f}translation")
                except XFormException:
                    nodes = []

                for translation_node in nodes:
                    lang = translation_node.attrib['lang']
                    for text_node in translation_node.findall("./{f}text"):
                        text_id = text_node.attrib['id']
                        itext_items[text_id] = itext_items.get(text_id, {})

                        for value_node in text_node.findall("./{f}value"):
                            value_form = value_node.attrib.get("form", "default")
                            value = ''
                            for part in ItextValue.from_node(value_node).parts:
                                if isinstance(part, ItextOutput):
                                    value += "<output value=\"" + part.ref + "\"/>"
                                else:
                                    value += mark_safe(force_text(part).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'))
                            itext_items[text_id][(lang, value_form)] = value

                for text_id, values in six.iteritems(itext_items):
                    row = [text_id]
                    for value_form in ["default", "audio", "image", "video"]:
                        # Get the fallback value for this form
                        fallback = ""
                        for lang in app.langs:
                            fallback = values.get((lang, value_form), fallback)
                            if fallback:
                                break
                        # Populate the row
                        for lang in app.langs:
                            row.append(values.get((lang, value_form), fallback))
                    # Don't add empty rows:
                    if any(row[1:]):
                        rows[form_string].append(row)
    return rows
Example #41
0
	def render(self,name,value,attrs=None):

		debug =""

	#	shows = Show.objects.all().order_by("english_title")
		shows = chain(Movie.objects.all().order_by("english_title"),TVShow.objects.all().order_by("english_title"))
		rowstart = ['<div class = "row" style="display: flex;">','','']
		rowend = ['', '', '</div>']

		content = ""
		counter = 0
		for show in shows:
			content = content + rowstart[counter%3]
			content =  content + '<div class = "col-sm-4 low_padding" style="outline:1px solid black;"><div class = "col-sm-6 low_padding"><img src = "'
			content = content + show.image.url
			content = content + '"class="img-rounded" align = "left" style="width:80px;height:100px"></div><div class="col-sm-6 low_padding"> <b id="'
			content = content + str(escape(show.id)) +  '"class = "show_names">' + escape(show.english_title.title()) + "</b>"
			content = content + "<br> <select id='season'> <option value="">all</option>"
			if hasattr(show,"total_seasons") and show.total_seasons > 1:
				for curr in range(show.total_seasons):
					content = content + "<option value = '" + str((curr + 1)) + "'> season " + str((curr + 1)) + "</option>"
			content = content + '</select><button = type="button" class="btn_show_selection">select</button></div></div>'
			content = content + rowend[counter%3]

			counter = counter + 1

		debug = debug + "out " + str((counter %3)) + ": "
		if counter %3 != 0:
			for curr in range(3 - (counter %3)):
				content = content + '<div class = "col-sm-4 low_padding" style="outline:1px solid black;"></div>'
				debug = debug + str((counter %3))
			content = content + "</div>"

		html = '<div class ="col-xs-4">'
		html = html + super(seriesWidget, self).render(name,value,attrs={"id" : "id_watch_order" ,"readonly":"True"})	
		html = html +"""

			  <br>
			<button type="button" class="btn btn-info btn-lg" id="btn_update">update</button>
			<button type="button" class="btn btn-info btn-lg" id="btn_clear">clear</button>
			</div>
			 <div class ="col-xs-4">
			 <h3><u>series order</u>
			 <!-- Trigger the modal with a button -->
			  <button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal">select shows</button>
			  </h3>
			<ol id ="the_list">
			</ol>
			</div>
			
			  <br>
			  
			  <!-- Modal -->
			  <div class="modal fade" id="myModal" role="dialog">
			    <div class="modal-dialog">
			    
			      <!-- Modal content-->
			      <div class="modal-content">
			        <div class="modal-header">
			          <button type="button" class="close" data-dismiss="modal">&times;</button>
			          <h4 class="modal-title">Modal Header</h4>
			        </div>
			        <div class="modal-body">
	        	""" + content + """
	        </div>
	        <div class="modal-footer">
	          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	        </div>
	      </div>
	      
	    </div>
	  </div>
			"""
		scripts = """
		<script>
	$(".btn_show_selection").click(function(event){
		var nameblock = $(this).siblings(".show_names");
		var img = $(this).siblings(".show_names");
		var selected_id = nameblock.attr("id");
		var title = nameblock.text();
		var season = $(this).siblings("#season").val();
		var li_id = "#" + selected_id +":"+ season;
		
		if(season != ""){
			season = ":" + season;
		}
		$("#the_list").append("<li id=" +selected_id + season + ">" +title + season + "</li>");
		$(nameblock).clone().appendTo("#the_lsit li:last-child").append("season" +season);

		$(".close").trigger("click");
	});
	
	$("#btn_update").click(function(event){
		$("#id_watch_order").val("");
		$("#the_list li").each(function(){
			var trimed = $.trim($(this).text());
			$("#id_watch_order").val( $("#id_watch_order").val() + $(this).attr("id") + ",");
		});
		$("#id_watch_order").val($("#id_watch_order").val().slice(0,-1));
	});
	
	$("#btn_clear").click(function(){
		$("#the_list").empty();
		$("#id_watch_order").val("");
	});
	
	$(function(){
		$("#the_list").sortable();
		$("#the_list").disableSelection();
	});
</script>
		"""

#		html = ""
#		for show in shows:
#			html= html + str(show.english_title)
		return mark_safe(html + scripts)
Example #42
0
File: tags.py Project: zjtisme/CRM
def display_all_related_objs(objs):

    if objs:
        model_class = objs[0]._meta.model
        model_name = objs[0]._meta.model_name
        return mark_safe(recursive_related_objs_lookup(objs))
Example #43
0
 def inner(model_admin):
     try:
         return mark_safe(json.dumps(f(model_admin)))
     except:
         return []
Example #44
0
 def get_photo(self, obj):
     if obj.photo:
         return mark_safe(f'<img src="{obj.photo.url}" width="75">')
     else:
         return 'Фото не установлено'
Example #45
0
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
    """
    Convert any URLs in text into clickable links.

    Works on http://, https://, www. links, and also on links ending in one of
    the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
    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, truncate the URLs in the link text longer
    than this limit to trim_url_limit-3 characters and append an ellipsis.

    If nofollow is True, give the links a rel="nofollow" attribute.

    If autoescape is True, autoescape the link text and URLs.
    """
    safe_input = isinstance(text, SafeData)

    def trim_url(x, limit=trim_url_limit):
        if limit is None or len(x) <= limit:
            return x
        return '%s...' % x[:max(0, limit - 3)]

    def unescape(text, trail):
        """
        If input URL is HTML-escaped, unescape it so that it can be safely fed
        to smart_urlquote. For example:
        http://example.com?x=1&amp;y=&lt;2&gt; => http://example.com?x=1&y=<2>
        """
        unescaped = (text + trail).replace('&amp;', '&').replace(
            '&lt;', '<').replace('&gt;',
                                 '>').replace('&quot;',
                                              '"').replace('&#39;', "'")
        if trail and unescaped.endswith(trail):
            # Remove trail for unescaped if it was not consumed by unescape
            unescaped = unescaped[:-len(trail)]
        elif trail == ';':
            # Trail was consumed by unescape (as end-of-entity marker), move it to text
            text += trail
            trail = ''
        return text, unescaped, trail

    def trim_punctuation(lead, middle, trail):
        """
        Trim trailing and wrapping punctuation from `middle`. Return the items
        of the new state.
        """
        # Continue trimming until middle remains unchanged.
        trimmed_something = True
        while trimmed_something:
            trimmed_something = False

            # Trim trailing punctuation.
            match = TRAILING_PUNCTUATION_RE.match(middle)
            if match:
                middle = match.group(1)
                trail = match.group(2) + trail
                trimmed_something = True

            # Trim wrapping punctuation.
            for opening, closing in WRAPPING_PUNCTUATION:
                if middle.startswith(opening):
                    middle = middle[len(opening):]
                    lead += opening
                    trimmed_something = True
                # Keep parentheses at the end only if they're balanced.
                if (middle.endswith(closing) and middle.count(closing)
                        == middle.count(opening) + 1):
                    middle = middle[:-len(closing)]
                    trail = closing + trail
                    trimmed_something = True
        return lead, middle, trail

    words = word_split_re.split(force_text(text))
    for i, word in enumerate(words):
        if '.' in word or '@' in word or ':' in word:
            # lead: Current punctuation trimmed from the beginning of the word.
            # middle: Current state of the word.
            # trail: Current punctuation trimmed from the end of the word.
            lead, middle, trail = '', word, ''
            # Deal with punctuation.
            lead, middle, trail = trim_punctuation(lead, middle, trail)

            # Make URL we want to point to.
            url = None
            nofollow_attr = ' rel="nofollow"' if nofollow else ''
            if simple_url_re.match(middle):
                middle, middle_unescaped, trail = unescape(middle, trail)
                url = smart_urlquote(middle_unescaped)
            elif simple_url_2_re.match(middle):
                middle, middle_unescaped, trail = unescape(middle, trail)
                url = smart_urlquote('http://%s' % middle_unescaped)
            elif ':' not in middle and simple_email_re.match(middle):
                local, domain = middle.rsplit('@', 1)
                try:
                    domain = domain.encode('idna').decode('ascii')
                except UnicodeError:
                    continue
                url = 'mailto:%s@%s' % (local, domain)
                nofollow_attr = ''

            # Make link.
            if url:
                trimmed = trim_url(middle)
                if autoescape and not safe_input:
                    lead, trail = escape(lead), escape(trail)
                    trimmed = escape(trimmed)
                middle = '<a href="%s"%s>%s</a>' % (escape(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 ''.join(words)
Example #46
0
def make_tbody_tr(
    lmv, obj, row_num, fields, extra_fields, only_date,
    verbose_name, to_field_name
):
    """Return tbody tr items."""
    opts = lmv.opts
    detail_link = obj.get_absolute_url
    update_link = obj.get_edit_url
    rowdata = ''
    for field_name in fields:
        td_format = '<td class="{}">{}</td>'
        td_text = ''
        td_class = "{}".format(field_name)
        if field_name == 'field-first':
            td_text = obj.pk
            td_format = '''<td class="no-print {}">
                <input type="checkbox" name="index" value="{}"></td>'''
        if field_name == 'field-second':
            td_text = row_num
            td_format = '<td class="{}">{}.</td>'
        if field_name == 'field-last':
            _edit = ''
            if can_change(opts, lmv.request.user):
                _edit = '''
                    <a title="编辑" href="{}">
                    <span class="label label-default margin-r-5">编辑</span>
                    </a>'''.format(update_link)
            _show = '''
                <a title="弹窗模式进行查看" href="{}"
                data-toggle="modal" data-target="#modal-lg">
                <span class="label label-default">查看</span>
                </a>'''.format(detail_link)
            td_text = mark_safe(_edit + _show)
            td_format = '<td class="no-print {}">{}</td>'
        if field_name not in extra_fields:
            td_class = "field-{}".format(field_name)
            td_format = '<td class="{}">{}</td>'
            classes = 'text-info'
            try:
                field = opts.get_field(field_name)
                value = field.value_from_object(obj)
                td_text = display_for_field(value, field, only_date=only_date)
                if field.name == to_field_name:
                    title = "点击查看 {} 为 {} 的详情信息".format(
                        opts.verbose_name, force_text(obj)
                    )
                    td_text = mark_safe(
                        '<a title="{}" href="{}">{}</a>'.format(
                            title, detail_link, td_text
                        )
                    )
                if getattr(field, 'flatchoices', None) \
                        or isinstance(field,
                                      (models.ForeignKey,
                                       models.BooleanField, models.NullBooleanField)):
                    link = lmv.get_query_string(
                        {'{}'.format(field.name): '{}'.format(value)}, ['page']
                    )
                    td_title = display_for_field(
                        value, field, html=False, only_date=only_date
                    )
                    title = "点击过滤 {} 为 {} 的所有 {}".format(
                        field.verbose_name, td_title, verbose_name
                    )
                    td_text = mark_safe(
                        '<a class="{}" title="{}" href="{}">{}</a>'.format(
                            classes, title, link, td_text
                        )
                    )
            except BaseException:
                _, _, _td_text = lookup_field(field_name, obj, obj._meta.model)
                td_text = mark_safe(_td_text)
        rowdata += format_html(td_format, td_class, td_text)
    return mark_safe(rowdata)
Example #47
0
from xadmin.sites import site
from xadmin.util import model_format_dict, model_ngettext
from xadmin.views import BaseAdminPlugin, ListAdminView
from xadmin.views.base import filter_hook, ModelAdminView

from xadmin import views

ACTION_CHECKBOX_NAME = '_selected_action'
checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)


def action_checkbox(obj):
    return checkbox.render(ACTION_CHECKBOX_NAME, force_text(obj.pk))


action_checkbox.short_description = mark_safe(
    '<input type="checkbox" id="action-toggle" />')
action_checkbox.allow_tags = True
action_checkbox.allow_export = False
action_checkbox.is_column = False


class BaseActionView(ModelAdminView):
    action_name = None
    description = None
    icon = 'fa fa-tasks'

    model_perm = 'change'

    @classmethod
    def has_perm(cls, list_view):
        return list_view.get_model_perms()[cls.model_perm]
Example #48
0
def escapejs(value):
    """Hex encode characters for use in JavaScript strings."""
    return mark_safe(str(value).translate(_js_escapes))
Example #49
0
 def render(self):
     return mark_safe('\n'.join(['%s\n' % w for w in self]))
Example #50
0
    def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
        "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
        top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for name, field in self.fields.items():
            html_class_attr = ''
            bf = self[name]
            # Escape and cache in local variable.
            bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
            if bf.is_hidden:
                if bf_errors:
                    top_errors.extend(
                        [_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': force_text(e)}
                         for e in bf_errors])
                hidden_fields.append(six.text_type(bf))
            else:
                # Create a 'class="..."' atribute if the row should have any
                # CSS classes applied.
                css_classes = bf.css_classes()
                if css_classes:
                    html_class_attr = ' class="%s"' % css_classes

                if errors_on_separate_row and bf_errors:
                    output.append(error_row % force_text(bf_errors))

                if bf.label:
                    label = conditional_escape(force_text(bf.label))
                    label = bf.label_tag(label) or ''
                else:
                    label = ''

                if field.help_text:
                    help_text = help_text_html % force_text(field.help_text)
                else:
                    help_text = ''

                output.append(normal_row % {
                    'errors': force_text(bf_errors),
                    'label': force_text(label),
                    'field': six.text_type(bf),
                    'help_text': help_text,
                    'html_class_attr': html_class_attr,
                    'field_name': bf.html_name,
                })

        if top_errors:
            output.insert(0, error_row % force_text(top_errors))

        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = ''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '</td></tr>') and
                # insert the hidden fields.
                if not last_row.endswith(row_ender):
                    # This can happen in the as_p() case (and possibly others
                    # that users write): if there are only top errors, we may
                    # not be able to conscript the last row for our purposes,
                    # so insert a new, empty row.
                    last_row = (normal_row % {'errors': '', 'label': '',
                                              'field': '', 'help_text':'',
                                              'html_class_attr': html_class_attr})
                    output.append(last_row)
                output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
            else:
                # If there aren't any rows in the output, just append the
                # hidden fields.
                output.append(str_hidden)
        return mark_safe('\n'.join(output))
Example #51
0
def order_detail(obj):
    return mark_safe('<a href="{}">View</a>'.format(
        reverse('orders:admin_order_detail', args=[obj.id])))
Example #52
0
 def get_raw_data(self, attachment):
     request = self.table.request
     return safestring.mark_safe(get_attachment_name(request, attachment))
Example #53
0
 def to_python(self, value):
     return mark_safe(value)
Example #54
0
def order_pdf(obj):
    return mark_safe('<a href="{}">PDF</a>'.format(
        reverse('orders:admin_order_pdf', args=[obj.id])))
Example #55
0
File: utils.py Project: Ale-/civics
def angular(file):
    return mark_safe("<script type='text/javascript' src='" + STATIC_URL +
                     PROJECT_STATIC_FOLDER + "/angular/" + file +
                     "'></script>")
Example #56
0
 def value_from_form(self, value):
     return mark_safe(value)
Example #57
0
 def onload(self):
     "Returns the `onload` HTML <body> attribute."
     # Overloaded to use the `load` function defined in the
     # `google-multi.js`, which calls the load routines for
     # each one of the individual maps in the set.
     return mark_safe('onload="%s.load()"' % self.js_module)
Example #58
0
 def get_default(self):
     return mark_safe(self.meta.default or '')
Example #59
0
class GoogleMap(object):
    "A class for generating Google Maps JavaScript."

    # String constants
    onunload = mark_safe('onunload="GUnload()"')  # Cleans up after Google Maps
    vml_css = mark_safe('v\:* {behavior:url(#default#VML);}')  # CSS for IE VML
    xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"'
                      )  # XML Namespace (for IE VML).

    def __init__(self,
                 key=None,
                 api_url=None,
                 version=None,
                 center=None,
                 zoom=None,
                 dom_id='map',
                 kml_urls=[],
                 polylines=None,
                 polygons=None,
                 markers=None,
                 template='gis/google/google-map.js',
                 js_module='geodjango',
                 extra_context={}):

        # The Google Maps API Key defined in the settings will be used
        # if not passed in as a parameter.  The use of an API key is
        # _required_.
        if not key:
            try:
                self.key = settings.GOOGLE_MAPS_API_KEY
            except AttributeError:
                raise GoogleMapException(
                    'Google Maps API Key not found (try adding GOOGLE_MAPS_API_KEY to your settings).'
                )
        else:
            self.key = key

        # Getting the Google Maps API version, defaults to using the latest ("2.x"),
        # this is not necessarily the most stable.
        if not version:
            self.version = getattr(settings, 'GOOGLE_MAPS_API_VERSION', '2.x')
        else:
            self.version = version

        # Can specify the API URL in the `api_url` keyword.
        if not api_url:
            self.api_url = getattr(settings, 'GOOGLE_MAPS_URL',
                                   GOOGLE_MAPS_URL) % self.version
        else:
            self.api_url = api_url

        # Setting the DOM id of the map, the load function, the JavaScript
        # template, and the KML URLs array.
        self.dom_id = dom_id
        self.extra_context = extra_context
        self.js_module = js_module
        self.template = template
        self.kml_urls = kml_urls

        # Does the user want any GMarker, GPolygon, and/or GPolyline overlays?
        overlay_info = [[GMarker, markers, 'markers'],
                        [GPolygon, polygons, 'polygons'],
                        [GPolyline, polylines, 'polylines']]

        for overlay_class, overlay_list, varname in overlay_info:
            setattr(self, varname, [])
            if overlay_list:
                for overlay in overlay_list:
                    if isinstance(overlay, overlay_class):
                        getattr(self, varname).append(overlay)
                    else:
                        getattr(self, varname).append(overlay_class(overlay))

        # If GMarker, GPolygons, and/or GPolylines are used the zoom will be
        # automatically calculated via the Google Maps API.  If both a zoom
        # level and a center coordinate are provided with polygons/polylines,
        # no automatic determination will occur.
        self.calc_zoom = False
        if self.polygons or self.polylines or self.markers:
            if center is None or zoom is None:
                self.calc_zoom = True

        # Defaults for the zoom level and center coordinates if the zoom
        # is not automatically calculated.
        if zoom is None: zoom = 4
        self.zoom = zoom
        if center is None: center = (0, 0)
        self.center = center

    def render(self):
        """
        Generates the JavaScript necessary for displaying this Google Map.
        """
        params = {
            'calc_zoom': self.calc_zoom,
            'center': self.center,
            'dom_id': self.dom_id,
            'js_module': self.js_module,
            'kml_urls': self.kml_urls,
            'zoom': self.zoom,
            'polygons': self.polygons,
            'polylines': self.polylines,
            'icons': self.icons,
            'markers': self.markers,
        }
        params.update(self.extra_context)
        return render_to_string(self.template, params)

    @property
    def body(self):
        "Returns HTML body tag for loading and unloading Google Maps javascript."
        return format_html('<body {0} {1}>', self.onload, self.onunload)

    @property
    def onload(self):
        "Returns the `onload` HTML <body> attribute."
        return format_html('onload="{0}.{1}_load()"', self.js_module,
                           self.dom_id)

    @property
    def api_script(self):
        "Returns the <script> tag for the Google Maps API javascript."
        return format_html(
            '<script src="{0}{1}" type="text/javascript"></script>',
            self.api_url, self.key)

    @property
    def js(self):
        "Returns only the generated Google Maps JavaScript (no <script> tags)."
        return self.render()

    @property
    def scripts(self):
        "Returns all <script></script> tags required with Google Maps JavaScript."
        return format_html(
            '{0}\n  <script type="text/javascript">\n//<![CDATA[\n{1}//]]>\n  </script>',
            self.api_script, mark_safe(self.js))

    @property
    def style(self):
        "Returns additional CSS styling needed for Google Maps on IE."
        return format_html('<style type="text/css">{0}</style>', self.vml_css)

    @property
    def xhtml(self):
        "Returns XHTML information needed for IE VML overlays."
        return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {0}>',
                           self.xmlns)

    @property
    def icons(self):
        "Returns a sequence of GIcon objects in this map."
        return set([marker.icon for marker in self.markers if marker.icon])
Example #60
0
def markdown_format(text):
    return mark_safe(markdown.markdown(text))