1. Germano Gabbianelli
  2. django-autocomplete-example

Source

django-autocomplete-example / ac / admin.py

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from autocomplete.views import autocomplete, AutocompleteSettings
from autocomplete.admin import AutocompleteAdmin
from ac.models import DummyModel, Language

class AdminSite(admin.AdminSite):
    login_template = 'login.html'

admin_site = AdminSite('ac')


class UserAutocomplete(AutocompleteSettings):
    search_fields = ('^username',)

class User2Autocomplete(UserAutocomplete):
    label = '%(first_name)s %(last_name)s'
    value = 'id'

class FriendsAutocomplete(UserAutocomplete):
    value = '%(first_name)s %(last_name)s'

    def label(self, u):
        return u'%s%s' % (u.email, ('',' (Staff)')[u.is_staff])

class EmailAutocomplete(UserAutocomplete):
    queryset = User.objects.all()
    key = value = 'email'
    limit = None

    def label(self, u):
        return u'%s %s<br><em>%s</em>' % (u.first_name, u.last_name, u.email)

class LanguageAutocomplete(AutocompleteSettings):
    search_fields = ('^name', '^designed_by')
    
    def value(self, l):
        return l.name.lower()

    def label(self, l):
        return '<img src="%s"> %s <span>designed by %s</span>' % (l.icon, l.name, l.designed_by) 

autocomplete.register(DummyModel.user1, UserAutocomplete)
autocomplete.register(DummyModel.user2, User2Autocomplete)
autocomplete.register(DummyModel.friends, UserAutocomplete)
autocomplete.register('ac.email', EmailAutocomplete)
autocomplete.register(DummyModel.favorite_language, LanguageAutocomplete)


class DummyAdmin(AutocompleteAdmin, admin.ModelAdmin):
    autocomplete_fields = {
        'email': 'ac.email',
    }

class LanguageAdmin(AutocompleteAdmin, admin.ModelAdmin):
    pass


admin_site.register(User, UserAdmin)
admin_site.register(DummyModel, DummyAdmin)
admin_site.register(Language, LanguageAdmin)