2012-08-24 11 views
26

Vorrei creare filtri personalizzati per l'admin di django anziché i normali 'is_staff' e 'is_superuser'. Ho letto questo list_filter in documenti Django. filtri personalizzati funzionano in questo modo:Creazione di filtri personalizzati per list_filter in Django Admin

from datetime import date 

from django.utils.translation import ugettext_lazy as _ 
from django.contrib.admin import SimpleListFilter 

class DecadeBornListFilter(SimpleListFilter): 
    # Human-readable title which will be displayed in the 
    # right admin sidebar just above the filter options. 
    title = _('decade born') 

    # Parameter for the filter that will be used in the URL query. 
    parameter_name = 'decade' 

    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. 
     """ 
     return (
      ('80s', _('in the eighties')), 
      ('90s', _('in the nineties')), 
     ) 

    def queryset(self, request, queryset): 
     """ 
     Returns the filtered queryset based on the value 
     provided in the query string and retrievable via 
     `self.value()`. 
     """ 
     # Compare the requested value (either '80s' or '90s') 
     # to decide how to filter the queryset. 
     if self.value() == '80s': 
      return queryset.filter(birthday__gte=date(1980, 1, 1), 
            birthday__lte=date(1989, 12, 31)) 
     if self.value() == '90s': 
      return queryset.filter(birthday__gte=date(1990, 1, 1), 
            birthday__lte=date(1999, 12, 31)) 

class PersonAdmin(ModelAdmin): 
    list_filter = (DecadeBornListFilter,) 

ma ho già fatto funzioni personalizzate per list_display come questo:

def Student_Country(self, obj): 
    return '%s' % obj.country 
Student_Country.short_description = 'Student-Country' 

E 'possibile ho potuto utilizzare le funzioni personalizzate per list_display in list_filter invece di scrivere una nuova funzione personalizzata per list_filter? Qualsiasi suggerimento o miglioramento sono graditi .. Hai bisogno di una guida su questo ... Grazie ...

+0

http: // StackOverflow. com/domande/12215751/can-i-make-list-filtro-in-django-admin-a-solo-show-referenziato-ForeignKeys – user956424

risposta

1

Il tuo list_display, metodo restituisce una stringa, ma se ho capito bene, quello che vuoi fare è aggiungere un filtro che permetta la selezione di paesi di studenti, corretto?

Per questo semplice filtro di relazione, e infatti anche per la colonna di visualizzazione dell'elenco "Paese studente", non è necessario creare una classe filtro personalizzata né un metodo di visualizzazione elenco personalizzato; questo basterebbe:

class MyAdmin(admin.ModelAdmin): 
    list_display = ('country',) 
    list_filter = ('country',) 

Il modo Django fa list_filter, come spiegato in the docs, è il primo da campi corrispondenza automaticamente forniti di pre-costruita classi dei filtri; questi filtri includono CharField e ForeignKey.

list_display automatizza in modo simile alla popolazione della colonna changelist utilizzando il campo passato recuperando gli oggetti correlati e restituendo il unicode il valore di questi (come nel metodo che hai fornito in precedenza).

5

È possibile infatti aggiungere filtri personalizzati ai filtri di amministrazione estendendo SimpleListFilter. Per esempio, se si desidera aggiungere un filtro continente 'Africa' al filtro Paese di amministrazione utilizzato in precedenza, è possibile effettuare le seguenti operazioni:

In admin.py:

from django.contrib.admin import SimpleListFilter 

class CountryFilter(SimpleListFilter): 
    title = 'country' # or use _('country') for translated title 
    parameter_name = 'country' 

    def lookups(self, request, model_admin): 
     countries = set([c.country for c in model_admin.model.objects.all()]) 
     return [(c.id, c.name) for c in countries] + [ 
      ('AFRICA', 'AFRICA - ALL')] 

    def queryset(self, request, queryset): 
     if self.value() == 'AFRICA': 
      return queryset.filter(country__continent='Africa') 
     if self.value(): 
      return queryset.filter(country__id__exact=self.value()) 

class CityAdmin(ModelAdmin): 
    list_filter = (CountryFilter,) 
Problemi correlati