admin.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from datetime import date
  4. from django.contrib import admin
  5. from django.contrib.auth import get_user_model
  6. from .models import ItemType, Item, Loan
  7. User = get_user_model()
  8. admin.site.register(ItemType)
  9. class OwnerFilter(admin.SimpleListFilter):
  10. title = "Propriétaire"
  11. parameter_name = 'owner'
  12. def lookups(self, request, model_admin):
  13. owners = [
  14. (i.pk, i) for i in User.objects.filter(items__isnull=False)]
  15. return [(None, "L'association")] + owners
  16. def queryset(self, request, queryset):
  17. if self.value():
  18. return queryset.filter(owner__pk=self.value())
  19. else:
  20. return queryset
  21. @admin.register(Item)
  22. class ItemAdmin(admin.ModelAdmin):
  23. list_display = (
  24. 'designation', 'type', 'mac_address', 'serial', 'owner',
  25. 'buy_date', 'is_available')
  26. list_filter = ('type__name', 'buy_date', OwnerFilter)
  27. search_fields = (
  28. 'designation', 'mac_address', 'serial',
  29. 'owner__email', 'owner__nickname',
  30. 'owner__first_name', 'owner__last_name')
  31. actions = ['give_back']
  32. def give_back(self, request, queryset):
  33. for item in queryset.filter(loans__loan_date_end=None):
  34. item.give_back()
  35. give_back.short_description = 'Rendre le matériel'
  36. @admin.register(Loan)
  37. class LoanAdmin(admin.ModelAdmin):
  38. list_display = ('item', 'user', 'loan_date', 'loan_date_end', 'location')
  39. list_filter = ('item__designation', 'user__username')
  40. search_fields = ('item', 'user')
  41. actions = ['end_loan']
  42. def end_loan(self, request, queryset):
  43. queryset.filter(loan_date_end=None).update(
  44. loan_date_end=date.today())
  45. end_loan.short_description = 'Mettre fin au prêt'