HTML input textbox in Django admin.py filter

Viewed 8979

I would like to filter data in Django (admin.py) with text writen in HTML input textbox. I need to filter companies by city in which they are and list of all cities is too long. I would like to replace list of all cities in filter by one text input. I found something similar here http://djangosnippets.org/snippets/2429/ but there are two problems:

  1. author did not posted models.py, so it is difficuilt to change code for my needs (+ no comments)
  2. there is used class UserFieldFilterSpec(RelatedFilterSpec): but I need to use AllValuesFilterSpec instead of RelatedFilterSpec (more in file django/contrib/admin/filterspecs.py), because list of towns are in the same class as comapny (there shoud by class of towns and they should be referencing to company by foreign key (ManyToMany relationship), but for some reasons it have to be done this way)

important part of models.py looks something like this

class Company(models.Model):
    title = models.CharField(max_length=150,blank=False)
    city = models.CharField(max_length=50,blank=True)

and something from admin.py

class CatalogAdmin(admin.ModelAdmin):
    form = CatalogForm
    list_display = ('title','city') 
    list_filter = ['city',]

So again, I need to: 1. instead of list od cities display one text input in Django filter 2. After inputing city neme in that text input, filter data by city (request for filtering can be sent with some submit button or through javascript)

Thank yoy for all posts.

4 Answers

Below is the fix for field name..in queryset function

class SingleTextInputFilter(admin.FieldListFilter):
"""
renders filter form with text input and submit button
"""

parameter_name = None
template = "admin/textinput_filter.html"

def __init__(self, field, request, params, model, model_admin, field_path):
    super().__init__(field, request, params, model, model_admin, field_path)
    if self.parameter_name is None:
        self.parameter_name = self.field.name

    if self.parameter_name in params:
        value = params.pop(self.parameter_name)
        self.used_parameters[self.parameter_name] = value

def queryset(self, request, queryset):

    variable_column = self.parameter_name
    search_type = 'icontains'
    filter = variable_column + '__' + search_type

    if self.value():
        return queryset.filter(**{filter: self.value()})
def value(self):
    """
    Returns the value (in string format) provided in the request's
    query string for this filter, if any. If the value wasn't provided then
    returns None.
    """
    return self.used_parameters.get(self.parameter_name, None)

def has_output(self):
    return True

def expected_parameters(self):
    """
    Returns the list of parameter names that are expected from the
    request's query string and that will be used by this filter.
    """
    return [self.parameter_name]

def choices(self, cl):
    all_choice = {
        'selected': self.value() is None,
        'query_string': cl.get_query_string({}, [self.parameter_name]),
        'display': ('All'),
    }
    return ({
        'get_query': cl.params,
        'current_value': self.value(),
        'all_choice': all_choice,
        'parameter_name': self.parameter_name
    }, )
Related