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>
{% 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.