Login

Filter by taggit tags in the admin (Django 1.4)

Author:
albertorcf
Posted:
August 31, 2012
Language:
Python
Version:
1.4
Tags:
filter tag admin tags tagging taggit
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. Filter by taggit tags in the admin by flupke 3 years, 5 months ago
  2. Dynamically insert or append a value to an admin option, e.g. list_display or list_filter by frankban 3 years, 7 months ago
  3. Alphabetic filter for admin by semente 6 years, 6 months ago
  4. IsNullFieldListFilter by ssokolow 2 years, 9 months ago
  5. FieldsetForm by Ciantic 7 years, 11 months ago

Comments

BenJahman (on August 19, 2013):

Works great.

#

Please login first before commenting.