Задать вопрос

Тел: +7 965 3737 888

462

Просмотров

6

Ответов

Alphabetic filter for admin

<p>This snippet is based on <a href="http://foothold.ru/knowledge/detail/alphabeticfilterspec.html">#748</a>.</p>
<p>Adds filtering by first char (alphabetic style) of values in the admin
filter sidebar. The example below results in this filter:</p>
By name that starts with
 All
 A
 B
 G
 M
 X

<p>urls.py example (only for register the filter):</p>
import &lt;your project&gt;.admin.filterspecs

<p>models.py example:</p>
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=40)
    name.alphabetic_filter = True

<p>admin.py example:</p>
class Admin:
    list_filter = ['name']

Вопрос полезен? Да0/Нет0
file_2332.py(1.9Кб)
None

Ответы (6):

Ответmartinvanbuuren:10.10.2011
Ответ полезен? Да0/Нет0

Solution to "'long' object is unsubscriptable"

Change

26 self.lookup_choices = list(set(val[0] for val in values_list if val))

to

26 self.lookup_choices = list(set(str(val)[0] for val in values_list if val))


This issue rises at ForeignKeys. The solution returns the first character of the id's rather than an error message.

Ответohnoimdead:15.05.2011
Ответ полезен? Да0/Нет0

Need to add field_path to init:

def __init__(self, f, request, params, model, model_admin, field_path=None):
    super(AlphabeticFilterSpec, self).__init__(f, request, params, model,
                                               model_admin,
                                               field_path=field_path)

Ответluc_j:10.11.2010
Ответ полезен? Да0/Нет0

Very helpful. I've made the following changes. I hope it helps

Avoid duplicates for lower and uppercase

self.lookup_choices = list(set(val.upper()[0] for val in values_list if val))

The register must be called explicitely

@classmethod
def register_filterspec(cls):
    """register the filter. To be called in the models.py"""
    FilterSpec.filter_specs.insert(0,
        (lambda f: getattr(f, 'alphabetic_filter', False), cls)
    )

Ответsemente:29.05.2009
Ответ полезен? Да0/Нет0

snippet updated.

magicrebirth, thanks for the tip.

Ответmagicrebirth:13.05.2009
Ответ полезен? Да0/Нет0

Line 55 is better changed like this:

self.lookup_choices = list(set(val[0] for val in values_list if val))

BY adding 'if val' it prevents the routine to crash when indexing items that are blank!

Ответbradmontgomery:14.01.2010
Ответ полезен? Да0/Нет0

Thanks! This is very helpful.