Login

Filter by first letter inclusion tag

Author:
slafs
Posted:
May 18, 2010
Language:
Python
Version:
1.2
Tags:
filter django-filter inclusion tag first-letter
Score:
0 (after 0 ratings)

My first snippet ;]

It's a simple inclusion tag for filtering a list of objects by a first letter using django-filter

after having this "installed" you can use it in your template like this:

{% load my_tags %}
<div class="letter_filter">
     Filter by first letter: {% letters_filter "MyNiceModel" %}
</div>

for information how to use django-filter in your view go to docs

you should probably cache this inclusion tag since it makes 45 queries to the db (.count() > 0)

Enjoy and improve ;]

PS. some parts of this code are in Polish

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# templatetags/my_tags.py

@register.inclusion_tag('tags/letters_filter.html')
def letters_filter(model):
    
    letters = u'0123456789AĄBCĆDEĘFGHIJKLŁMNŃOPÓQRSŚTUVWXYZŹŻ'
    ModelClass = get_model('subjects', model) # could make it even more generic here ('subjects' is my app name)
    if ModelClass is None:
        raise TemplateSyntaxError("Nie ma takiego modelu %s" % model)
    letters_list = [letter for letter in letters \
                    if ModelClass._default_manager.filter(my_nice_field_name__istartswith=letter).count() > 0]
    ret_dict = { 'letters_list' : letters_list }
    
    return ret_dict

# template "tags/letters_filter.html"

{% if letters_list %}
	{% for letter in letters_list %}
		<a href="?firstletter={{letter}}">{{letter|upper}}</a>&nbsp;
	{% endfor %}
	<a href="?">All</a>
{% endif %}

# filters.py

import django_filters

class MyNiceFilterSet(django_filters.FilterSet):
    firstletter = django_filters.CharFilter(lookup_type='istartswith', name='my_nice_field_name' )

    class Meta:
        model = MyNiceModel

More like this

  1. Pagination/Filtering Alphabetically by zain 6 years, 3 months ago
  2. Python Calendar wrapper template tag by dokterbob 6 years, 2 months ago
  3. Page numbers with ... like in Digg by Ciantic 6 years, 2 months ago
  4. really spaceless (trim spaces at line start) by wolfram 7 years, 5 months ago
  5. Make tags easier with properties by ubernostrum 8 years, 4 months ago

Comments

Please login first before commenting.