Login

Active User Sorted ModelAdmin

Author:
daemondazz
Posted:
July 2, 2009
Language:
Python
Version:
1.0
Tags:
sorting modeladmin user-foreign-key
Score:
0 (after 0 ratings)

Since r7806, the User field is unsorted which makes it harder to find specific users in the list if there is more than a few. This snippet is an django.contrib.admin.ModelAdmin subclass which searches through all of the fields on a form and automatically sorts fields which have a relation with User. It also filters on having active=True.

Just import the SortedActiveUserModelAdmin class in your admin.py and subclass your ModelAdmin classes from it instead of admin.ModelAdmin.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# ----- helpers/admin.py -----
from django.contrib import admin
from django.contrib.auth.models import User

class SortedActiveUserModelAdmin(admin.ModelAdmin):
     def get_form(self, request, obj=None):
         form = super(SortedActiveUserModelAdmin, self).get_form(request, obj)
         for fieldname, field in form.base_fields.items():
             if hasattr(field.widget, 'rel') and field.widget.rel.to == User:
                 field.queryset = field.queryset.filter(is_active=True).order_by('username')
         return form


# ----- myapp/admin.py -----
from django.contrib import admin
from helpers.admin import SortedActiveUserModelAdmin
from myapp.models import MyModel

class MyModelAdmin(SortedActiveUserModelAdmin):
     pass

admin.site.register(MyModel, MyModelAdmin)

More like this

  1. Multiple User subclasses custom Auth backend by ungenio41 3 years, 8 months ago
  2. Django Admin Replacer Code by riccardodivirgilio 4 years, 6 months ago
  3. Admin: ordering by multiple fields in a column sort by benatkin 4 years, 10 months ago
  4. Allow multiple field sorting in a single admin table column by matiascelasco 2 months ago
  5. restrict user access to modeladmin via metaclass by code_shogan 4 years, 3 months ago

Comments

Please login first before commenting.