Login

Filter by taggit tags in the admin (Django 1.4)

Author:
albertorcf
Posted:
August 31, 2012
Language:
Python
Version:
1.4
Score:
3 (after 3 ratings)

A SimpleListFilter derived class that can be used to filter by taggit tags in the admin.

To use, simply add this class to the list_filter attribute of your ModelAdmin class.

Ex.:

class ItemAdmin(admin.ModelAdmin):
  list_display = ('name', 'unit', 'amount')
  list_filter = ('unit', TaggitListFilter)

Based in ModelAdmin.list_filter documentation.

 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
34
35
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from taggit.models import TaggedItem 

class TaggitListFilter(SimpleListFilter):
  """
  A custom filter class that can be used to filter by taggit tags in the admin.
  """

  # Human-readable title which will be displayed in the
  # right admin sidebar just above the filter options.
  title = _('tags')

  # Parameter for the filter that will be used in the URL query.
  parameter_name = 'tag'
  
  def lookups(self, request, model_admin):
    """
    Returns a list of tuples. The first element in each tuple is the coded value
    for the option that will appear in the URL query. The second element is the
    human-readable name for the option that will appear in the right sidebar.
    """
    list = []
    tags = TaggedItem.tags_for(model_admin.model)
    for tag in tags:
      list.append( (tag.name, _(tag.name)) )
    return list    

  def queryset(self, request, queryset):
    """
    Returns the filtered queryset based on the value provided in the query
    string and retrievable via `self.value()`.
    """
    if self.value():
      return queryset.filter(tags__name__in=[self.value()])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

BenJahman (on August 19, 2013):

Works great.

#

Please login first before commenting.