Atterratio
Atterratio

Reputation: 466

How to make a filter on my own field in django admin?

I added a boolean field is calculated from the time like this:

def is_active(self):
    if self.inactive_to and self.available_until:
        if datetime.date.today()>=self.inactive_to and datetime.date.today()<=self.available_until:
            return True
        else:
            return False
    elif self.inactive_to:
        if datetime.date.today()>=self.inactive_to:
            return True
        else:
            return False
    elif self.available_until:
        if datetime.date.today()<=self.available_until:
            return True
        else:
            return False
    else:
        return True
is_active.short_description = 'Available'
is_active.boolean = True

But if I try add it to "list_filter" I get error "'RealtyAdmin.list_filter[0]' refers to 'is_active' which does not refer to a Field."

I can avoid it, or add in model fild that will be calculated automatically?

Upvotes: 4

Views: 3125

Answers (4)

Steve K
Steve K

Reputation: 11369

The Django ORM cannot find a database field named is_active, because it's a python function. The Django admin does not enable sorting or filtering by python function returned results. However, as you said, you can add a field to your model which contains the value you want, and then add it to list_filter.

Upvotes: 0

Atterratio
Atterratio

Reputation: 466

I was not enough attentive, here https://docs.djangoproject.com/en/1.5/ref/contrib/admin/ is a description of how to add your own filter (from 1.4)

Upvotes: 2

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48982

It sounds like you're confusing list_display and list_filter. Your code is for adding a new column in the list_display but your title and error message refer to list_filter.

Upvotes: 0

eugene
eugene

Reputation: 21

admin is not a field which subclassed from django.db.models.fields.

That's what 'is_active' which does not refer to a Field." is saying..

Upvotes: 2

Related Questions