Filter by taggit tags in the admin (Django 1.4)

 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. Filter by taggit tags in the admin by flupke 2 years, 6 months ago
  2. Dynamically insert or append a value to an admin option, e.g. list_display or list_filter by frankban 2 years, 8 months ago
  3. Alphabetic filter for admin by semente 5 years, 7 months ago
  4. IsNullFieldListFilter by ssokolow 1 year, 9 months ago
  5. Exists Filter OneToOneField in Admin by davidvaz 2 years, 5 months ago

Comments

BenJahman (on August 19, 2013):

Works great.

#

(Forgotten your password?)