Pages

08 November 2012

Django contrib admin SimpleListFilter


models.py
------------------------------------------------------------

class identity(models.Model):
  ...
  def getStatus(self):
    if (identitytoken.objects.filter(Q(identity=self.pk) &
                                      (Q(expires__isnull=True) |
                                       Q(expires__gte=datetime.date.today()))).count()==0):
      return "inactive"
    else:
      return "active"

class identitytoken(models.Model):
  identity = models.ForeignKey("identity")
  expires = models.DateField(null=True, blank=True)
  ...

class person(identity):
  person_identity= models.OneToOneField("identity", primary_key=True, parent_link=True)
  ...

admin.py
------------------------------------------------------------
class StatusFilter(SimpleListFilter):
  title          = "Status"
  parameter_name = 'status'

  def lookups(self, request, model_admin):
    return (
      ("active", "active"),
      ("inactive", "inactive"),
    )

  def queryset(self, request, queryset):
    if self.value() == u"active":
      return queryset.filter()
    if self.value() == u"inactive":
      return queryset.filter()
    return queryset

class PersonAdmin(admin.ModelAdmin):
  fields          = ("name", "getStatus", ...)
  list_display    = ("name", "getStatus", )
  list_filter     = (StatusFilter, )
  readonly_fields = ("getStatus", )

0 comments: