Browse Source

Improve Loan admin filters

- display only relevant users
- filter by status
Jocelyn Delande 9 years ago
parent
commit
e44983e17e
1 changed files with 54 additions and 2 deletions
  1. 54 2
      hardware_provisioning/admin.py

+ 54 - 2
hardware_provisioning/admin.py

@@ -48,11 +48,63 @@ class ItemAdmin(admin.ModelAdmin):
             item.give_back()
     give_back.short_description = 'Rendre le matériel'
 
+
+class StatusFilter(admin.SimpleListFilter):
+    title = 'Statut'
+    parameter_name = 'status'
+
+    def lookups(self, request, model_admin):
+        return [
+            ('all', 'Tout'),
+            (None, 'En cours'),
+            ('finished', 'Passés'),
+        ]
+
+    def choices(self, cl):
+        for lookup, title in self.lookup_choices:
+            yield {
+                'selected': self.value() == lookup,
+                'query_string': cl.get_query_string({
+                    self.parameter_name: lookup,
+                }, []),
+                'display': title,
+            }
+
+    def queryset(self, request, queryset):
+        v = self.value()
+        if v in (None, 'running'):
+            return queryset.running()
+        elif v == 'finished':
+            return queryset.finished()
+        else:
+            return queryset
+
+
+class BorrowerFilter(admin.SimpleListFilter):
+    title = 'Adhérent emprunteur'
+    parameter_name = 'user'
+
+    def lookups(self, request, model_admin):
+        users = set()
+        for loan in model_admin.get_queryset(request):
+            users.add((loan.user.pk, loan.user))
+        return users
+
+    def queryset(self, request, queryset):
+        if self.value():
+            return queryset.filter(user=self.value())
+        else:
+            return queryset
+
+
 @admin.register(Loan)
 class LoanAdmin(admin.ModelAdmin):
     list_display = ('item', 'user', 'loan_date', 'loan_date_end')
-    list_filter = ('item__designation', 'user__username')
-    search_fields = ('item', 'user')
+    list_filter = (StatusFilter, BorrowerFilter, 'item__designation')
+    search_fields = (
+        'item__designation',
+        'user__nickname', 'user__username',
+        'user__first_name', 'user__last_name', )
     actions = ['end_loan']
 
     def end_loan(self, request, queryset):