Esempio n. 1
0
def natural_text(obj):
    if isinstance(obj, bool):
        return "はい" if obj is True else "いいえ"

    # 文字列の場合は、空文字の場合も「(なし)」と表示させるが、数値などはそのまま表示させるため、別々に処理
    if isinstance(obj, str):
        return urlize_with_target_blank(obj) if obj else "(なし)"

    if isinstance(obj, datetime):
        return localize(localtime(obj))

    if isinstance(obj, date):
        return localize(obj)

    if isinstance(obj, Model) and hasattr(obj, "get_absolute_url"):
        return safe(f"<a href='{obj.get_absolute_url()}'>{obj}</a>")

    if isinstance(obj, ImageFieldFile):
        if obj:
            # 画像埋め込み
            return safe(f"<img src='{obj.url}'>")
        else:
            return "(なし)"

    if obj is None:
        return "(なし)"

    return urlize_with_target_blank(obj)
Esempio n. 2
0
def format_header(column, order):
    """
    Decides how the column's header should be formatted, and what "order" it's href should have.

    :param column: the table header to determine the current title and url for
    :param order: the active table ordering
    :returns: a dictionary with the header title and url
    """
    result = {'title': None, 'url': None}

    col_l = column.lower().replace(' ', '')
    if "-" + col_l == order:
        # if col_l is "points" and order is "-points", the column title should be "Points-"
        result['title'] = column.capitalize() + " <i class='fa fa-chevron-down'></i>"
        # don't escape the html
        result['title'] = defaultfilters.safe(result['title'])
        # if col_l is "points" and order is "-points", clicking Points url should order results with "points"
        result['url'] = col_l
    else:
        # if col_l is "points" and current sort is "points", clicking Points url should order results with "-points"
        # or, if col_l is "points" and order is "skill", clicking Points url should default order results with "-points"
        result['url'] = "-" + col_l
        if col_l == order:
            # if col_l is "points" and current sort is "points", the column title should be "Points+"
            result['title'] = column.capitalize() + " <i class='fa fa-chevron-up'></i>"
            # don't escape the html
            result['title'] = defaultfilters.safe(result['title'])
        else:
            # if col_l is "points" and current sort is "skill", the column title should be "Points"
            result['title'] = column.capitalize()
    return result
Esempio n. 3
0
def linker(link):
    if link.startswith("http"):
        return safe(u'href="{0}" target="_blank"'.format(link, ))
    elif link != "":
        return safe(u'href="/{1}{0}"'.format(link, get_language()))
    else:
        return safe('style="cursor:pointer;"')
Esempio n. 4
0
def with_prefix(thread):
    if thread.prefix:
        return safe("<span class='badge' style='background: #" +
                    thread.prefix.color + "; color:white;'>" +
                    thread.prefix.name + "</span> " + thread.title)
    else:
        return safe(thread.title)
def render_news_placeholder(context, obj, name=False, truncate=False):
    """
    Template tag to render a placeholder from an object, which has a
    placeholders many-to-many-field.

    """
    result = ''
    if context.get('request') and hasattr(obj, 'placeholders'):
        if isinstance(name, int):
            # If the user doesn't want to use a placeholder name, but a cut, we
            # need to check if the user has used the name as a number
            truncate = name
            name = False
        if name:
            # If the name of the placeholder slot is given, get, render and
            # return it!
            try:
                result = safe(obj.placeholders.get(slot=name).render(
                    context, None))
            except ObjectDoesNotExist:
                pass
        else:
            # If no name is provided get the first placeholder with content
            for placeholder in obj.placeholders.all():
                rendered = safe(placeholder.render(context, None))
                if rendered:
                    result = rendered
                    break
    if truncate:
        return truncatewords_html(result, truncate)
    return result
Esempio n. 6
0
def format_header(column, order):
    """
    Decides how the column's header should be formatted, and what "order" it's href should have.

    :param column: the table header to determine the current title and url for
    :param order: the active table ordering
    :returns: a dictionary with the header title and url
    """
    result = {'title': None, 'url': None}

    col_l = column.lower().replace(' ', '')
    if "-" + col_l == order:
        # if col_l is "points" and order is "-points", the column title should be "Points-"
        result['title'] = column.capitalize(
        ) + " <i class='fa fa-chevron-down'></i>"
        # don't escape the html
        result['title'] = defaultfilters.safe(result['title'])
        # if col_l is "points" and order is "-points", clicking Points url should order results with "points"
        result['url'] = col_l
    else:
        # if col_l is "points" and current sort is "points", clicking Points url should order results with "-points"
        # or, if col_l is "points" and order is "skill", clicking Points url should default order results with "-points"
        result['url'] = "-" + col_l
        if col_l == order:
            # if col_l is "points" and current sort is "points", the column title should be "Points+"
            result['title'] = column.capitalize(
            ) + " <i class='fa fa-chevron-up'></i>"
            # don't escape the html
            result['title'] = defaultfilters.safe(result['title'])
        else:
            # if col_l is "points" and current sort is "skill", the column title should be "Points"
            result['title'] = column.capitalize()
    return result
Esempio n. 7
0
def new_post(blog_id, username, password, post, publish):
    """metaWeblog.newPost(blog_id, username, password, post, publish)
    => post_id"""
    user = authenticate(username, password)
    if post.get('dateCreated'):
        pub_date = datetime.strptime(
            post['dateCreated'].value.replace('Z', '').replace('-', ''),
            '%Y%m%dT%H:%M:%S')
    else:
        pub_date = datetime.now()

    entry_dict = {'title': post['title'],
                  'body': safe(removetags(post['description'],HTML_TAGS)),
                  'html_body': safe(post['description']),
                  'pub_date': pub_date,
                  'published': 1,
                  'last_update': pub_date,
                  'comment_enabled': post.get('mt_allow_comments', 1) == 1,
                  'slug': slugify(post['title']),
                  }
    entry = Post.objects.create(**entry_dict)

    if 'categories' in post:
        entry.categories.add(*[Category.objects.get_or_create(
                        title=cat, slug=slugify(cat))[0]
                        for cat in post['categories']])
    
    if 'tags' in post:
        entry.tags.add(*[Tag.objects.get_or_create(
                        title=tag, slug=slugify(tag))[0]
                        for tag in post['tags']])

    return entry.pk
Esempio n. 8
0
 class Meta:
     model = Organization
     fields = [
         'name',
         'url',
         'email',
         'address',
         'city',
         'state',
         'postal_code',
         'country',
         'founded',
         'media_url',
         'logo_url',
     ]
     labels = {
         'name':
         _('What is the name of your enterprise or project?'),
         'url':
         _('What is the URL of your enterprise or project?'),
         'email':
         _('What is the general contact email address for your enterprise or project?'
           ),
         'socialnetworks':
         _('What are the social media handles of your enterprise or project?'
           ),
         'address':
         _(
             safe(
                 'What is the physical address of the headquarters of your enterprise or project?<br/> Street'
             )),
         'state':
         _('State or province'),
         'founded':
         _(
             safe(
                 'When was your enterprise or project founded? (Year required. <span class="required"> *</span>)'
             )),
         'media_url':
         _('Paste a link to photos or any introductory video about your enterprise or project:'
           ),
         'logo_url':
         _('Paste a link to the logo for your enterprise or project:'),
     }
     help_texts = {}
     widgets = {
         'url':
         URLInput(attrs={'placeholder': 'e.g., https://example.coop/'}),
         'founded':
         DateSelectorWidget(),
         'media_url':
         URLInput(attrs={
             'placeholder':
             'e.g., https://www.youtube.com/watch?v=qcPUARqRsVM'
         }),
         'logo_url':
         URLInput(
             attrs={'placeholder': 'e.g., https://example.coop/logo.png'}),
     }
Esempio n. 9
0
def reputation(user):
    rep = user.userprofile.get_reputation()
    if rep > 0:
        return safe("<span class='text-success'>" + str(rep) + "</span>")
    elif rep < 0:
        return safe("<span class='text-danger'>" + str(rep) + "</span>")
    else:
        return safe("<span class='text-warning'>0</span>")
Esempio n. 10
0
    def __getitem__(self, name):
        item = super().__getitem__(name)
        prefix = "" if self.prefix is None else self.prefix + "-"

        if self.error_orient == AjaxFormErrorsLocation.TOP:
            return safe(_TOP_ERRORS_WRAPPER_DIV % (prefix + name, item))
        elif self.error_orient == AjaxFormErrorsLocation.BOTTOM:
            return safe(_BOTTOM_ERRORS_WRAPPER_DIV % (item, prefix + name))
Esempio n. 11
0
 def get_yayin_taslak_html(self):
     if self.yayin_taslak == 'taslak':
         return safe(
             '<span style="vertical-align:text-top;font-size:15px" class="label label-{1}">{0}</span>'
             .format(self.get_yayin_taslak_display(), 'danger'))
     return safe(
         '<span style="vertical-align:text-top;font-size:15px" class="label label-{1}">{0}</span>'
         .format(self.get_yayin_taslak_display(), 'primary'))
Esempio n. 12
0
def merged_cell(mc: MergedCell):
    if mc is None:
        return safe('<td>None</td>')
    inner = render_value(
        mc.values[0].value) if mc.valid else render_invalid(mc)
    class_name = 'valid' if mc.valid else 'invalid'
    order_attr = f' data-order="{mc.sort_order}"' if mc.sort_order is not None else ''
    return safe(f'<td class="{class_name}"{order_attr}>{inner}</td>')
Esempio n. 13
0
def fix_json_string(string):
    """
    Marks a string as not requiring further HTML escaping prior to output.
    """
    string = safe(string)
    string = string.replace('"\\"',"'").replace('\\"\"', "'") # fix quotes
    string = cut(string,"\"") # keep fixing
    string = safe(string)  # keep fixing
    return string
Esempio n. 14
0
    def get_yayin_taslak_html(self):
        if self.yayin_taslak == 'taslak':
            return safe('<span class="label label-danger">{0}</span>'.format(
                self.get_yayin_taslak_display()))
            # veya böylede yazabiliriz:
            #return '<span class="label label-{0}">{1}</span>'.format('danger',self.get_yayin_taslak_display())

        return safe('<span class="label label-primary">{0}</span>'.format(
            self.get_yayin_taslak_display()))
Esempio n. 15
0
 def get_yayin_taslak_html(self):
     if self.yayin_taslak == 'taslak':
         return safe(
             '<small><span class="label label-{1}">{0}</span></small>'.
             format(self.get_yayin_taslak_display(), 'danger'))
     else:
         return safe(
             '<small><span class="label label-{1}">{0}</span></small>'.
             format(self.get_yayin_taslak_display(), 'success'))
Esempio n. 16
0
 def clean_description(self):
     description = self.cleaned_data["description"]
     if spam_blacklist.is_spam(description):
         email = settings.EMAIL_CONTACT_US
         raise forms.ValidationError(defaultfilters.safe("This job description has triggered our spam filter. " \
             "If this is a legitimate job, please contact us at <a href='mailto:%(email)s?subject=Job Marked as Spam'>%(email)s</a>." % locals()))
     if not config_value("website", "ALLOW_LINKS_IN_JOBS"):
         if re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', description):
             raise forms.ValidationError(defaultfilters.safe("Sorry, links are not allowed in job descriptions." % locals()))
     return description
Esempio n. 17
0
 def get_context_data(self, **kwargs):
     context = super(CheckoutView, self).get_context_data()
     profile = self.request.user.get_profile()
     context['profile'] = profile
     context['checkout'] = urlencode(self.request.path_info)
     if not profile.billing_address:
         messages.warning(self.request, safe('Please fill <a href="%s">billing address</a>.' % (
         reverse('edit_address_redirect', args=('1', context['checkout'])),)))
     if not profile.shipping_address:
         messages.warning(self.request, safe('Please fill <a href="%s">shipping address</a>.' % (
         reverse('edit_address_redirect', args=('2', context['checkout'])),)))
     context['can_process'] = profile.billing_address and profile.shipping_address
     return context
Esempio n. 18
0
    def save(self, *args, **kwargs):
        if not self.pk:  # pylint: disable=E0203
            self.pk = make_nl_id()

        if not self.created:  # pylint: disable=E0203
            self.created = datetime.today()

        # Make sure that the subject is below the limit (which could happen
        # if it's generated from a template)
        if len(self.subject) > SUBJECT_MAX_LENGTH:
            self.subject = self.subject[:SUBJECT_MAX_LENGTH - 3] + '...'

        if self.is_source() and not self.frozen:
            if self.from_name == '':
                self.from_name = self.type.default_from_name
            if self.from_email == '':
                self.from_email = self.type.default_from_email
            if self.editorial_text == '' and self.editorial:
                self.editorial_text = defaultfilters.striptags(
                    unescape(defaultfilters.safe(self.editorial)))

            self.render({})

            for local in self.translations.all():
                local.render({})
                local.save()

        elif self.is_translation():
            try:
                language = NewsletterLanguage.objects.get(
                    language__lang=self.lang, newsletter_type=self.source.type)
                if self.from_name == '' and language.default_from_name:
                    self.from_name = language.default_from_name
                if self.from_email == '' and language.default_from_email:
                    self.from_email = language.default_from_email

                if self.editorial == '' and language.default_editorial:
                    self.editorial = language.default_editorial
                if self.editorial_text == '' and language.default_editorial_text:
                    self.editorial_text = language.default_editorial_text

                if self.editorial_text == '' and self.editorial:
                    self.editorial_text = defaultfilters.striptags(
                        unescape(defaultfilters.safe(self.editorial)))
            except NewsletterLanguage.DoesNotExist:
                # This should only happen if we try to save a NL for which the
                # NewsletterLanguage doesn't exist any longer
                pass

        return super(Newsletter, self).save()
Esempio n. 19
0
def showUpcomming(request, who, amount=10, pageIndex=1):
    if who == "anonymous":
        hs, created = History.objects.get_or_create(owner=None)
    elif who == "auto":
        # automatically get username from request
        hs, created = History.objects.get_or_create(owner__username=request.user.username)
    else:
        # 'who' is an username (string)
        hs, created = History.objects.get_or_create(owner__username=who)
    if created:            
        hs.save()
    isFirst = (pageIndex == 1) # could be used to show a header
    
    if getattr(settings, 'HISTORY_USE_UTC', False):
        now = datetime.utcnow()
    else:
        now = datetime.now()
        
    futureEvents = hs.events.filter(event_timestamp__gte=now).exclude(is_hidden=True).exclude(
        is_internal=True).order_by('event_timestamp')
    paginator = Paginator(futureEvents, amount)
    thisPage = paginator.page(pageIndex)
    hasMore = thisPage.has_next()
    listOfFutureEvents = thisPage.object_list
    
    return safe(render_to_string('history/upcomming.html', {'listOfFutureEvents': listOfFutureEvents,
                                                             'events': listOfFutureEvents,
                                                          'hasMore': hasMore,
                                                          'isFirst': isFirst,
                                                          'pageIndex': pageIndex,
                                                         }, context_instance=RequestContext(request)))
Esempio n. 20
0
def disarm_user_input(html):
    """ 
    Returns html without posible harm
    In addition
    - urlizes text if no links are used
    - breaks lines if no paragraphs are used
    """
    html = defaultfilters.removetags(html, "script style comment")
    # remove javascript events and style attributes from tags
    re_comments = re.compile(r'<!--[\s\S]*?(-->|$)')
    re_tags = re.compile(r'(<[^>\s]+)([^>]+)(>)')
    re_attrs = re.compile(
        r"""\s+(on[^=]+|style)=([^"'\s]+|"[^"]*"|'[^']*')""",
        )
    def remove_js_events(match):
        return "".join((
            match.group(1),
            re_attrs.sub('', match.group(2)),
            match.group(3),
            ))
    html = re_comments.sub("", html)
    html = re_tags.sub(remove_js_events, html)
    if "</a>" not in html:
        html = defaultfilters.urlizetrunc(html, "30")
    if "</p>" not in html:
        html = defaultfilters.linebreaks(html)
    html = defaultfilters.safe(html)
    return html
Esempio n. 21
0
    def __init__(self, url):
        base.ServiceHandlerBase.__init__(self, url)
        self.proxy_base = None
        self.url = url
        self.parsed_service = ArcMapService(self.url)
        extent, srs = utils.get_esri_extent(self.parsed_service)
        try:
            _sname = utils.get_esri_service_name(self.url)
            _title_safe = safe(os.path.basename(os.path.normpath(_sname)))
            _title = _title_safe.replace('_', ' ').strip()
        except Exception:
            traceback.print_exc()
            _title = self.parsed_service.mapName
        if len(_title) == 0:
            _title = utils.get_esri_service_name(self.url)
        # wkt_geometry = utils.bbox2wktpolygon([
        #     extent['xmin'],
        #     extent['ymin'],
        #     extent['xmax'],
        #     extent['ymax']
        # ])

        self.indexing_method = INDEXED
        self.name = slugify(self.url)[:255]
        self.title = _title
Esempio n. 22
0
def html_tel(phones, joiner=' / '):
    array_to_process = phones.split(',')
    array_to_response = []
    for row in array_to_process:
        array_to_response.append('<a href="tel:{0}">{1}</a>'.format(
            tel(row), row.strip()))
    return safe(joiner.join(array_to_response, ))
Esempio n. 23
0
 def infobox_status(self, obj: Region) -> str:
     result = ''
     if obj.id is not None:
         for key, value in obj.infobox_status(get_language()).items():
             name = 'icon-{}.svg'.format('yes' if value else 'no')
             result += '<img src="{}" title="{}"/>'.format(static('admin/img/' + name), key)
     return safe(result)
Esempio n. 24
0
def init_menu_vign(_tab, _lim) :

	# Import
	from django.template.defaultfilters import safe

	'''
	Initialisation d'une ligne de vignettes
	_prem : Indice du tableau _tab (première vignette de la future ligne)
	_nbre : Nombre de vignettes
	Retourne un tableau
	'''
	def init_lg(_prem, _nbre) :
		return ['<div class="col-sm-{0}">{1}</div>'.format(int(12 / _nbre), _tab[_prem + i]) for i in range(0, _nbre)]

	# Stockage du nombre de vignettes
	long_tab = len(_tab)

	# Stockage du nombre de lignes complètes
	nb_lg = int(long_tab / _lim)

	# Initialisation des lignes (complètes et incomplète)
	tab_lg = []
	for i in range(0, nb_lg) : tab_lg.append('<div class="row">{}</div>'.format(''.join(init_lg(i * _lim, _lim))))
	nb_vign_rest = long_tab % _lim
	if nb_vign_rest > 0 :
		tab_lg.append('<div class="row">{}</div>'.format(''.join(init_lg(nb_lg * _lim, nb_vign_rest))))

	# Mise en forme du menu à vignettes
	menu_vign = '<div class="thumbnails-row">{}</div>'.format(''.join(tab_lg)) if len(tab_lg) > 0 else ''

	return safe(menu_vign)
Esempio n. 25
0
def external_urlize(value, autoescape=None):
    from django.template.defaultfilters import urlize

    value = urlize(value, autoescape)
    value = value.replace("a href", 'a rel="external" href')

    return safe(value)
Esempio n. 26
0
def diff_text(a, b):
    s = SequenceMatcher(None, a, b)
    opcode = {'replace': lambda i1, i2, j1, j2: "<strike>%s</strike><strong>%s</strong>" % (a[i1:i2], b[j1:j2]),
              'delete': lambda i1, i2, j1, j2: "<strike>%s</strike>" % (a[i1:i2], ),
              'insert': lambda i1, i2, j1, j2: "<strong>%s</strong>" % (b[j1:j2], ),
              'equal': lambda i1, i2, j1, j2: a[i1:i2]}
    return safe("".join(opcode[tag](*args) for tag, *args in s.get_opcodes()))
Esempio n. 27
0
 def render_tag(self, context, placeholder, width, language=None):
     request = context.get('request', None)
     if not request:
         return ''
     if not placeholder:
         return ''
     return safe(placeholder.render(context, width, lang=language))
Esempio n. 28
0
def edit_post(post_id, username, password, post, publish):
    """metaWeblog.editPost(post_id, username, password, post, publish)
    => boolean"""
    user = authenticate(username, password, 'zinnia.change_entry')
    entry = Post.objects.get(id=post_id)
    if post.get('dateCreated'):
        pub_date = datetime.strptime(
            post['dateCreated'].value.replace('Z', '').replace('-', ''),
            '%Y%m%dT%H:%M:%S')
    else:
        pub_date = entry.creation_date

    entry.title = post['title']
    entry.html_body = post['description']
    entry.body = safe(removetags(entry.html_body,HTML_TAGS))
    entry.pub_date = pub_date
    entry.last_update = datetime.datetime.now()
    entry.comment_enabled = post.get('mt_allow_comments', 1) == 1
    entry.slug = 'wp_slug' in post and post['wp_slug'] or slugify(
        post['title'])
    entry.save()

    if 'categories' in post:
        entry.categories.clear()
        entry.categories.add(*[Category.objects.get_or_create(
            title=cat, slug=slugify(cat))[0]
                               for cat in post['categories']])
    
    if 'tags' in post:
        entry.tags.add(*[Tag.objects.get_or_create(
                        title=tag, slug=slugify(tag))[0]
                        for tag in post['tags']])

    return True
Esempio n. 29
0
def linkEmails(str_to_process, joiner=' / '):
    array_to_process = str_to_process.split(',')
    array_to_response = []
    for row in array_to_process:
        array_to_response.append('<a href="mailto:{0}">{0}</a>'.format(
            row.strip(), ))
    return safe(joiner.join(array_to_response, ))
Esempio n. 30
0
def post_to_email(obj):
    email_list = GamerUser.objects.values_list('email', flat=True).filter(is_active=True, buletin_notification=True)
    subject, text_content, html_content = obj.getEmailText()
    msg = EmailMultiAlternatives(subject, filters.safe(filters.striptags(text_content)), settings.BULETIN_FROM_EMAIL, bcc=email_list)
    msg.attach_alternative(html_content, "text/html")
    msg.send()
    return True
Esempio n. 31
0
 def render_tag(self, context, placeholder, width):
     request = context.get('request', None)
     if not request:
         return ''
     if not placeholder:
         return ''
     return safe(placeholder.render(context, width))
Esempio n. 32
0
def form_query(request, query_id):
    query = Query.objects.get(id=query_id)
    form = QueryForm(initial={'text': query.text}, query=query)
    context = {
        'title':
        'Run Query %s on database %s' %
        (force_unicode(query.name), query.database),
        'form':
        form,
        'object_id':
        query_id,
        'original':
        query,
        'media':
        safe(
            """<script type="text/javascript" src="{0}admin/js/core.js"></script>
                    <script type="text/javascript" src="{0}admin/js/jquery.js"></script>
                    <script type="text/javascript" src="{0}admin/js/jquery.init.js"></script>"""
            .format(settings.STATIC_URL)),
        'is_popup':
        "_popup" in request.REQUEST,
        'app_label':
        query._meta.app_label,
        'opts':
        query._meta,
        'change':
        False,
    }
    return render_to_response('requery/query.html',
                              context,
                              context_instance=RequestContext(request))
Esempio n. 33
0
def init_fm_perm(_req):

    # Imports
    from app.apps import AppConfig
    from app.functions import init_fm
    from app.models import TUtilisateur
    from django.template.defaultfilters import safe

    # Initialisation des fenêtres modales
    if _req.user.is_authenticated():

        # Obtention d'une instance TUtilisateur
        obj_util = TUtilisateur.objects.get(pk=_req.user.pk)

        tab_fm = [
            init_fm(
                'ger_mode_super_secr', '{} le mode super-secrétaire'.format(
                    'Activer' if obj_util.get_est_super_secr() ==
                    False else 'Désactiver')),
            init_fm(
                'logout', 'Déconnexion de la plateforme {}'.format(
                    AppConfig.verbose_name))
        ]
    else:
        tab_fm = []

    return {'modals': safe(''.join(tab_fm))}
Esempio n. 34
0
    def _get_value(self, context, editable=True, **kwargs):
        request = context.get('request', None)
        placeholder = kwargs.get('placeholder')
        width = kwargs.get('width')
        nocache = kwargs.get('nocache', False)
        language = kwargs.get('language')
        if not request:
            return ''
        if not placeholder:
            return ''

        if isinstance(placeholder, string_types):
            placeholder = PlaceholderModel.objects.get(slot=placeholder)
        if not hasattr(request, 'placeholders'):
            request.placeholders = {}
        perms = (placeholder.has_change_permission(request) or not placeholder.cache_placeholder)
        if not perms or placeholder.slot not in request.placeholders:
            request.placeholders[placeholder.slot] = (placeholder, perms)
        else:
            request.placeholders[placeholder.slot] = (
                placeholder, perms and request.placeholders[placeholder.slot][1]
            )
        context = copy(context)
        return safe(placeholder.render(context, width, lang=language,
                                       editable=editable, use_cache=not nocache))
Esempio n. 35
0
    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()

        # validate if email exists in our database
        try:
            User.objects.get(email=cleaned_data.get('email', None))
            self._errors['email'] = self.error_class([_(safe('Your email already exists in our system. If you do not remember your password try our recovery <a href="%s">here</a>. ' % reverse('accounts-login')))])
            del cleaned_data['email']
        except User.DoesNotExist:
            pass

        # validate if passwords are matching & not less than 8 characters
        try:

            if cleaned_data.get('password', None) != cleaned_data.get('password_confirm', None):
                self._errors['password'] = self.error_class(
                    [_('Password does not match.')])
                del cleaned_data['password']

            elif len(cleaned_data.get('password', '')) < getattr(settings, 'GARAGE_PASSWORD_LENGTH', 8):
                self._errors['password'] = self.error_class(
                    [_('Password cannot be less than 8 characters.')])
                del cleaned_data['password']

        except KeyError as e:
            self._errors['password'] = self.error_class(
                [_('Password error cannot be blank.')])

        return cleaned_data
Esempio n. 36
0
 def clean_message(self):
     message = self.cleaned_data["message"]
     if re.search("<a href=\"https?://|\[link=https?://|\[url=https?://", message):
         email = settings.EMAIL_CONTACT_US
         raise forms.ValidationError(defaultfilters.safe("This message has triggered our spam filter. " \
             "If this is a legitimate message, please contact us at <a href='mailto:%(email)s?subject=Candidate Message Marked as Spam'>%(email)s</a>." % locals()))
     return message
Esempio n. 37
0
def set_consts(_req) :

	# Import
	from app.apps import AppConfig
	from app.functions.modal_init import sub as modal_init
	from app.models import TUtilisateur
	from django.template.defaultfilters import safe

	# Tentative d'obtention d'une instance TUtilisateur
	obj_util_connect = TUtilisateur.get_util_connect(_req)

	# Déclaration des fenêtres modales permanentes
	if obj_util_connect :
		modals = [
			modal_init(
				'ger_mode_superadmin',
				'{} le mode super-administrateur'.format(
					'Activer' if obj_util_connect.get_est_superadmin() < 1 else 'Désactiver'
				)
			),
			modal_init('logout', 'Déconnexion de la plateforme {}'.format(AppConfig.verbose_name))
		]
	else :
		modals = []

	return {
		'app_name' : AppConfig.verbose_name,
		'connected_user' : TUtilisateur.get_util_connect(_req),
		'permanent_modals' : safe(''.join(modals))
	}
Esempio n. 38
0
def action(name,
           url,
           icon,
           size="h4",
           show_name=False,
           new_tab=False,
           enabled=True):
    """
    This function is used to generate HTML for an action

    @param name: The name of the action
    @type name: str
    @param url: The url the action leads to
    @type url: str
    @param icon: The fontawesome icon class to show
    @type icon: str
    @param size: The size (class) of the icon
    @type size: str
    @param show_name: Whether to show the name of the action next to the icon
    @type show_name: bool
    @param new_tab: Whether to open the url in a new tab
    @type show_name: bool
    @param enabled: If the action is enables
    @type enabled: bool
    @return: An HTML String that represents the action
    @rtype: str
    """

    tab_target = "target=\"_blank\""
    return safe(
        f'<a aria-label="{title(name)}" {tab_target if new_tab else ""} class="{"" if enabled else "disabled"}'
        f' {slugify(name)} {"labeled" if show_name else ""} navigation-action" href="{url}">'
        f'<i class="fas {icon} {slugify(name)}-icon {size}">{title(name) if show_name else ""}'
        f'</i>'
        f'</a>')
Esempio n. 39
0
 def render_tag(self, context, placeholder, width, language=None):
     request = context.get("request", None)
     if not request:
         return ""
     if not placeholder:
         return ""
     return safe(placeholder.render(context, width, lang=language))
Esempio n. 40
0
    def _get_value(self, context, editable=True, **kwargs):
        request = context.get('request', None)
        placeholder = kwargs.get('placeholder')
        width = kwargs.get('width')
        nocache = kwargs.get('nocache', False)
        language = kwargs.get('language')
        if not request:
            return ''
        if not placeholder:
            return ''

        if isinstance(placeholder, string_types):
            placeholder = PlaceholderModel.objects.get(slot=placeholder)
        if not hasattr(request, 'placeholders'):
            request.placeholders = {}
        perms = (placeholder.has_change_permission(request)
                 or not placeholder.cache_placeholder)
        if not perms or placeholder.slot not in request.placeholders:
            request.placeholders[placeholder.slot] = (placeholder, perms)
        else:
            request.placeholders[placeholder.slot] = (
                placeholder, perms
                and request.placeholders[placeholder.slot][1])
        context = copy(context)
        return safe(
            placeholder.render(context,
                               width,
                               lang=language,
                               editable=editable,
                               use_cache=not nocache))
Esempio n. 41
0
def br(text):
    '''
        Convierte dos barras inclinadas en un salto de línea
    '''

    text = text.replace('//', '<br>')
    return safe(text)
Esempio n. 42
0
def nolinks(value: str):
    """Убирает из html гиперссылки.

    :param value:

    """
    return safe(f"{RE_HREF.sub('', value)}")
Esempio n. 43
0
def generateExpireTime(userInfo):
    item = '<span class="layui-badge %s">%s</span>'
    if not userInfo.isExpire():
        html = item % ('layui-bg-green', formatDate(userInfo.expireTime))
    else:
        html = item % ('', formatDate(userInfo.expireTime))
    return safe(html)
Esempio n. 44
0
    def report_individual_sales(self, is_csv=False):
        # todo: make event specific
        tickets = Ticket.objects.filter(
            is_abandoned=False
        ).prefetch_related(
            'danceclasssurvey',
            'dancepasssurvey',
            'attendee',
            'paypal_ipn_set',
            'ticketaddon_set',
            'ticketaddon_set__ticket__paypal_ipn_set',
            'ticketaddon_set__ticket__ticketaddon_set',
        ).order_by(
            'created_at'
        ).reverse()

        header = 'id, Name, Email, Role, Ticket Type, Add Ons, Ticket Cost, Received, Pending'.split(',')
        rows = []
        total_owed = total_cost = total_paid = 0
        for t in tickets:
            if t.is_expirable:
                t.is_abandoned = True
                t.notes += "Abandoned due to expiry at %s. " % datetime.datetime.now(datetime.timezone.utc).strftime('%m/%d/%Y %H:%M:%S')
                t.release_all_addons()
                t.save()

            if t.should_invoice:
                # the ticket is not yet pending or paid so skip it
                continue

            if t.is_canceled and not t.is_cancelation_finalized:
                t.set_cancelation_amount_due()
                t.release_all_addons()
                continue

            addons = t.ticketaddon_set.all()
            addon_names = [a.ticketaddon_type.name for a in addons]
            addons_string = ', '.join(addon_names)
            role = 'INCOMPLETE SURVEY'
            if t.survey:
                role = t.survey.dance_role
            rows.append(
                (
                    str(t.id) if is_csv else safe('<a href="/admin/ticket/ticket/{id}/">{id}</a>'.format(id=t.id)),
                    t.attendee.get_full_name(),
                    t.attendee.email,
                    role,
                    t.ticket_type.name,
                    addons_string,
                    t.adj_price,
                    t.amount_paid,
                    t.amount_pending
                ))
            total_paid += t.amount_paid
            total_cost += t.adj_price
            total_owed += t.amount_pending
        rows.append(('Total', '', '', '', '', '', total_cost, total_paid, total_owed))
        roll_up_dict = {}
        return header, rows, roll_up_dict
Esempio n. 45
0
 def toHTML(self):
     text = self.enunciat
     canvi = ""
     if self.tipus.nom == "CompletarGramatica":
         canvi = "<input class='resposta' type='text'><br>"
     if self.tipus.nom == "EmplenarBuitsOrtografics":
         canvi = "<input class='form-control  inputPetit resposta' type='text'>"
     return safe(re.sub(r'\[\w+\]',canvi, text))
Esempio n. 46
0
def errors(field, attrs={}):
    """ Uses to get a field errors """
    template_errors = u'<div class="help-block">{0}</div>'
    template_error = u'<p>{0}</p>'
    if field.errors:
        errors = [template_error.format(error) for error in field.errors]
        return safe(template_errors.format("".join(errors)))
    return ""
Esempio n. 47
0
 def render_tag(self, context, insertion_point, width):
     inserter, created = Insert.objects.get_or_create(insertion_point = insertion_point)
     request = context.get('request', None)
     if not request:
         return ''
     if not inserter.content:
         return ''
     return safe(inserter.content.render(context, width))
Esempio n. 48
0
def goodreads_get_search_tag(query):
    """Возврщает тег ссылки на поиск ISBN по сайту Goodreads.

    :param query:
    :return:
    """
    url = 'https://www.goodreads.com/search/?%s' % urlencode({'query': query})
    return safe('<a href="%s" title="ISBN на goodreads.com">%s</a>' % (url, query))
Esempio n. 49
0
def empty(value, default=""):
    # Value can either be safe HTML or text.
    if value:
        return conditional_escape(value)
    else:
        if not default:
            default = _("empty")
        return safe("%s%s%s" % ('<span class="lighter smaller">', conditional_escape(default), "</span>"))
Esempio n. 50
0
 def print_stars(self):
     html = ''
     if self.stars: stars = int(round(float(self.stars) * 4))
     else: stars = 0
     for i in range(1, 21):
         if i == stars: html += '<input name="st_%s" type="radio" class="star" disabled="disabled" checked="checked"/>\n' % self.article
         else: html += '<input name="st_%s" type="radio" class="star {split:4}" disabled="disabled"/>\n' % self.article
     return safe(html)
Esempio n. 51
0
File: auth.py Progetto: boxed/curia
def linebreaks_and_spaces(value):
    import re
    value = value.replace('\n\n', '<p></p>\n')
    value = re.sub('([^>])\n', '\g<1><br />\n', value)
    pattern = re.compile(r'\n[ \t]+')
    from curia.feedparser import _sanitizeHTML
    from django.template.defaultfilters import safe
    return safe(pattern.sub(replace_spaces, _sanitizeHTML(value, settings.DEFAULT_CHARSET)))
Esempio n. 52
0
 def get_help_text(self):
     help_text = ' '
     if self.help_text_template:
         tmpl = template.loader.get_template(self.help_text_template)
         context = template.RequestContext(self.request)
         help_text += tmpl.render(context)
     else:
         help_text += linebreaks(force_unicode(self.help_text))
     return safe(help_text)
 def render_tag(self, context, name, extra_bits, varname):
     output = super(PlaceholderAs, self).render_tag(
         context, name, extra_bits)
     output_template = Template(safe(output))
     output_rendered = output_template.render(context)
     if varname:
         context[varname] = output_rendered
         return ''
     return output_rendered
Esempio n. 54
0
def goodreads_get_search_tag(query):
    """Возврщает тег ссылки на поиск ISBN по сайту Goodreads.

    :param query:
    :return:
    """
    url = 'https://www.goodreads.com/search/?%s' % urlencode({'query': query})
    return safe(
        '<a href="%s" title="Искать на goodreads.com"><span class="glyphicon glyphicon-search"></span></a>' % url)
Esempio n. 55
0
 def render_tag(self, context, placeholder, width, height):
     request = context.get('request', None)
     if not request:
         return ''
     if not placeholder:
         return ''
     if hasattr(request, 'placeholder_media'):
         request.placeholder_media += placeholder.get_media(request, context)
     return safe(placeholder.render(context, width, height))
Esempio n. 56
0
 def get_help_text(self, extra_context=None):
     text = ""
     extra_context = extra_context or {}
     if self.help_text_template:
         tmpl = template.loader.get_template(self.help_text_template)
         text += tmpl.render(extra_context, self.request)
     else:
         text += defaultfilters.linebreaks(force_text(self.help_text))
     return defaultfilters.safe(text)
Esempio n. 57
0
def ticket_sales_totals_report(is_csv=False):
    ticket_types = models.TicketType.objects.all().distinct('id')
    header = 'id,Ticket Type,Quantity Sold,Max Capacity,Leads,Follows,Revenue,Received,Pending'.split(',')
    rows = []
    total_tickets_purchased = total_leaders = total_followers = total_capacity = 0
    paypal_fees = total_revenue = total_received = total_pending = 0
    for ticket_type in ticket_types:
        survey_type = ticket_type.survey_form_type.Meta.model.__name__.lower()
        tickets = ticket_type.ticket_set.filter(
            is_abandoned=False
        ).prefetch_related(
            'ticketaddon_set',
            'paypal_ipn_set',
        )
        survey_q = survey_type + '__dance_role'
        num_leaders = tickets.filter(is_canceled=False, **{survey_q: 'lead'}).count()
        num_followers = tickets.filter(is_canceled=False, **{survey_q: 'follow'}).count()
        revenue = received = pending = 0

        for t in tickets:
            revenue += t.adj_price
            received += t.amount_paid
            pending += t.amount_pending
            paypal_fees += t.mc_fee

        rows.append(
            (
                ticket_type.id if is_csv else safe('<a href="/admin/ticket/tickettype/{id}/">{id}</a>'.format(id=ticket_type.id)),
                ticket_type.name,
                tickets.count(),
                ticket_type.capacity,
                num_leaders,
                num_followers,
                revenue,
                received,
                pending
            )
        )
        total_capacity += ticket_type.capacity
        total_tickets_purchased += len(tickets.filter(is_canceled=False))
        total_revenue += revenue
        total_received += received
        total_pending += pending
        total_leaders += num_leaders
        total_followers += num_followers
    rows.append(('Total', '', total_tickets_purchased, total_capacity, total_leaders, total_followers, total_revenue, total_received, total_pending))

    roll_up_dict = OrderedDict((
        ('Total Revenue', total_revenue),
        ('Total Received', total_received),
        ('Total Pending', total_pending),
        ('Total PayPal Fees', paypal_fees),
        ('Net Revenue', total_revenue - paypal_fees),
        ('Received Net Revenue', total_received - paypal_fees),
    ))
    return header, rows, roll_up_dict