- Author:
- daemondazz
- Posted:
- July 2, 2009
- Language:
- Python
- Version:
- 1.0
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.