django.template.defaulttags.register.filter - python examples

Here are the examples of the python api django.template.defaulttags.register.filter taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

52 Examples 7

3 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def board_url(board):
    """Return the URL for the board, including the slug if available."""
    # In the future, we might just want to directly use get_absolute_url in the template. However, this extra level
    # of indirection gives us some additional flexibility
    return board.get_absolute_url() if board is not None else None

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def srv_perms(v):
  output = []
  for field in v._meta.get_fields():
    if isinstance(field, BooleanField):
      name = field.name.split('can_')[1].capitalize().replace('_', ' ')
      output.append([field.help_text, name, getattr(v, field.name)])

  output = sorted(output, key=lambda x: x[0])
  return output

3 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def detail_name(eval_):
    """Return the human-readable name for the given evaluation."""
    if eval_:
        return next(e[1] for e in Evaluation.EVALUATION_OPTIONS if e[0] == eval_.value)
    else:
        return _('No astessments')

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def m2m_duration(m2m):
  total = datetime.timedelta()
  for delta in m2m.all():
    disconnected = delta.disconnected if delta.disconnected else timezone.now()
    total += disconnected - delta.connected

  return total

3 View Complete Implementation : gennotes_helpers.py
Copyright MIT License
Author : madprime
@register.filter
def markdown(value):
    """
    Translate markdown to a safe subset of HTML.
    """
    cleaned = bleach.clean(markdown_library.markdown(value),
                           tags=bleach.ALLOWED_TAGS +
                           ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])

    linkified = bleach.linkify(cleaned)

    return mark_safe(linkified)

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def get(value, key):
  if isinstance(value, dict):
    return value.get(key)
  else:
    return value[int(key)]

3 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def detail_clastname(eval_):
    """Return the CSS style astociate with the given evaluation."""
    mapping = {
        None: "eval-no-astessments",
        Eval.consistent: "eval-consistent",
        Eval.inconsistent: "eval-inconsistent",
        Eval.very_inconsistent: "eval-very-inconsistent",
        Eval.very_consistent: "eval-very-consistent",
        Eval.not_applicable: "eval-not-applicable",
        Eval.neutral: "eval-neutral"
    }
    result = mapping.get(eval_)
    return result

3 View Complete Implementation : gennotes_helpers.py
Copyright MIT License
Author : madprime
@register.filter
def parse_gennotes_citations(clinvar_relation_data):
    citations = clinvar_relation_data['tags'].get('clinvar-rcva:citations')
    if citations:
        return citations.split(';')
    return citations

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def mask(target, modifier='0.75'):
  target = str(target)

  start = len(target) - (len(target) * float(modifier))

  result = ""
  for i in range(len(target)):
    if i >= start and target[i] != '-':
      result += "●"
    else:
      result += target[i]

  return result

3 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def created(value):
  user = api.ISteamUser.GetPlayerSummaries(steamids=value)['response']
  timestamp = user['players'][0]['timecreated']

  return humanize.naturaltime(datetime.datetime.fromtimestamp(timestamp))

3 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def vac(value):
  ban = api.ISteamUser.GetPlayerBans(steamids=value)['players'][0]
  if ban['VACBanned']:
    return "currently banned"
  elif ban['DaysSinceLastBan'] == 0:
    return "no recorded ban"
  else:
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=ban['DaysSinceLastBan'])
    return "expired {}".format(natural.date.duration(now - delta))

3 View Complete Implementation : report_tags.py
Copyright MIT License
Author : madprime
@register.filter
def variant_flags(row_data):
    flags = []

    # Variant level contradicted flag: add only if there are notes, and all
    # notes are "contradicted".
    all_contradicted = True if row_data['gennotes_data'] else False
    for item in row_data['gennotes_data']:
        if item['tags']['evidence'] != 'contradicted':
            all_contradicted = False
    if row_data['unclaimed_rcvs']:
        all_contradicted = False
    if all_contradicted:
        flags.append('flag-contradicted')

        # Default report is to hide all "contradicted" effects.
        if 'hidden' not in flags:
            flags.append('hidden')
    return ' '.join(flags)

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
@register.filter
def user_display_string(user):
    if user.first_name and user.last_name:
        return "{} {}".format(user.first_name, user.last_name)
    elif user.email:
        return user.email
    return user.username

3 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def bootstrap_alert(tags):
    """Return the Bootstrap alert CSS clast for the given Django message level tag.

    Requires the message to only contain a single tag. For more information, see:
        https://docs.djangoproject.com/en/1.10/ref/contrib/messages/#message-tags
    """
    mapping = {
        'debug': 'alert-info',
        'info': 'alert-info',
        'success': 'alert-success',
        'warning': 'alert-warning',
        'error': 'alert-error',
    }
    return mapping[tags] if tags in mapping else tags

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def permission_percentage(value):
  data = value.permissions.all().count() if isinstance(value, (Group, Token)) else len(value.get_all_permissions())

  if data == 0:
    return "0"

  return str(int(round(data / Permission.objects.all().count() * 100)))

3 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def duration(delta):
  if isinstance(delta, str):
    return ''

  now = datetime.datetime.now()
  return natural.date.delta(now, now + delta, words=False)[0]

3 View Complete Implementation : dict_utils.py
Copyright MIT License
Author : chris48s
@register.filter
def get_clast(dictionary, key):
    el = dictionary.get("method_" + key, None)
    if el:
        return el["clast"]
    return ""

3 View Complete Implementation : humanizer.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def get_groups_id(value):
  if value.is_superuser or not value.groups.all():
    return ""

  return value.groups.all()[0].id

3 View Complete Implementation : report_tags.py
Copyright MIT License
Author : madprime
@register.filter
def note_flags(item):
    flags = []

    # Note level contradicted flag.
    if item['tags']['evidence'] == 'contradicted':
        flags.append('flag-contradicted')
        # Default report is to hide all "contradicted" effects.
        if 'hidden' not in flags:
            flags.append('hidden')

    return ' '.join(flags)

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def flatten(value, location):
  return list(map(lambda x: x[int(location)], value))

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def warp(duration):
  now = datetime.datetime.now()
  return now + duration

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def count(obj):
  return obj.count()

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def userconnection(v):
  connection = v.userconnection_set.order_by('-created_at')[0]
  return timezone.now() - connection.connected

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def gen_srv_perms(v):
  return srv_perms(ServerPermission())

0 View Complete Implementation : report_tags.py
Copyright MIT License
Author : madprime
@register.filter
def space_after_colon(string):
    return re.sub(r':', ': ', string)

0 View Complete Implementation : report_tags.py
Copyright MIT License
Author : madprime
@register.filter
def inheritance_display(inheritance):
    if inheritance == 'other_or_unknown':
        return 'other/unknown'
    return inheritance

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def day(day):
  return natural.date.day(day)

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
@register.filter
def sort_items(dictionary):
    return sorted(dictionary.items())

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def contains(collection, element):
    """Return True if collection contains element."""
    return element in collection

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def disagreement_category(value):
    """Return a human-readable description of the level of disagreement given by the value."""
    return _('No astessments') if value is None else _dispute_level(value).name

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def disagreement_style(value):
    """Return the CSS clast name astociated with the given level of disagreement."""
    return 'disagree-no-astessments' if value is None else _dispute_level(value).css_clast

0 View Complete Implementation : get_attribute.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ddaan
@register.filter
def get_attribute(value, arg, return_as_string=True):
    """
    Gets an attribute of an object dynamically from a string name
    """
    numeric_test = re.compile("^\d+$")

    if hasattr(value, '__iter__') and arg in value:
        value = value[arg]
    elif hasattr(value, str(arg)):
        value = getattr(value, arg)
    elif numeric_test.match(str(arg)) and len(value) > int(arg):
        value = value[int(arg)]
    else:
        return settings.TEMPLATE_STRING_IF_INVALID

    if hasattr(value, '__call__'):
        value = value()

    if return_as_string:
        value = mark_safe(value)

    return value

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def canonical_reverse(request, url_name):
    """Return the canonical URI for url_name."""
    # this should probably be a tag that calls the url template method and then builds the absolute uri
    return request.build_absolute_uri(reverse(url_name))

0 View Complete Implementation : utils.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def isoduration(v):
  return isodate.duration_isoformat(v)

0 View Complete Implementation : report_tags.py
Copyright MIT License
Author : madprime
@register.filter
def significance_display(significance):
    if significance == 'risk_factor':
        return 'risk factor'
    return significance

0 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def get_clast(obj):
    """Return the clast name of obj."""
    return obj.__clast__.__name__

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def canonical_url(request, model):
    """Return the canonical URL of the model, including domain, and excluding slugs and parameters."""
    return request.build_absolute_uri(model.get_canonical_url())

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def dict_get(dictionary, key):
    """Return the value for key in dictionary or None."""
    return dictionary.get(key, None)

0 View Complete Implementation : get_attribute.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ddaan
@register.filter
def get_attribute_recursive(value, arg, return_as_string=True):
    """
    Gets an attribute of an object dynamically from a string name
    """
    if arg is None:
        return mark_safe("")

    if '__' in arg:
        arg_list = arg.split('__')
    elif '.' in arg:
        arg_list = arg.split('.')
    else:
        arg_list = [arg]

    for arg in arg_list:
        value = get_attribute(value, arg, return_as_string=False)

    if return_as_string:
        value = mark_safe(value)

    return value

0 View Complete Implementation : jsonify.py
Copyright Apache License 2.0
Author : IBM-Blockchain-Identity
@register.filter
def jsonify(dictionary):
    if not type(dictionary) is type({}):
        return None
    return json.dumps(dictionary, indent=2)

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def canonical_profile_url(request, user):
    """Return the canonical URL of the user's public profile."""
    return request.build_absolute_uri(reverse('profile', args=(user.id,)))

0 View Complete Implementation : humanizer.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def get_server_name(value):
  return Server.objects.get(id=value).name

0 View Complete Implementation : humanizer.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def get_groups_name(value):
  return value.groups.all()[0].name

0 View Complete Implementation : board_extras.py
Copyright GNU General Public License v3.0
Author : twschiller
@register.filter
def full_url(request, model):
    """Return the URL of the model, including domain."""
    return request.build_absolute_uri(model.get_absolute_url())

0 View Complete Implementation : get_item.py
Copyright Apache License 2.0
Author : IBM-Blockchain-Identity
@register.filter
def get_item(dictionary, key):
    if not type(dictionary) is type({}):
        return None
    return dictionary.get(key)

0 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def as32(value):
  return SteamID(value).as_32

0 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def as2(value):
  return SteamID(value).as_steam2

0 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def as3(value):
  return SteamID(value).as_steam3

0 View Complete Implementation : steam.py
Copyright GNU Lesser General Public License v3.0
Author : indietyp
@register.filter
def level(value):
  return api.IPlayerService.GetSteamLevel(steamid=value)['response']['player_level']