admin.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.contrib import admin
  4. from django.contrib.auth import get_user_model
  5. from django.forms import ModelChoiceField
  6. from django.utils import timezone
  7. import autocomplete_light
  8. from .models import ItemType, Item, Loan, Storage
  9. import coin.members.admin
  10. User = get_user_model()
  11. admin.site.register(ItemType)
  12. class OwnerFilter(admin.SimpleListFilter):
  13. title = "Propriétaire"
  14. parameter_name = 'owner'
  15. def lookups(self, request, model_admin):
  16. owners = [
  17. (i.pk, i) for i in User.objects.filter(items__isnull=False)]
  18. return [(None, "L'association")] + owners
  19. def queryset(self, request, queryset):
  20. if self.value():
  21. return queryset.filter(owner__pk=self.value())
  22. else:
  23. return queryset
  24. class AvailabilityFilter(admin.SimpleListFilter):
  25. title = "Disponibilité"
  26. parameter_name = 'availability'
  27. def lookups(self, request, model_admin):
  28. return [
  29. ('available', 'Disponible'),
  30. ('unavailable', 'Indispo (emprunté ou déployé)'),
  31. ('borrowed', 'Emprunté'),
  32. ('deployed', 'Déployé'),
  33. ]
  34. def queryset(self, request, queryset):
  35. if self.value() == 'available':
  36. return queryset.available()
  37. elif self.value() == 'unavailable':
  38. return queryset.unavailable()
  39. elif self.value() == 'borrowed':
  40. return queryset.borrowed()
  41. elif self.value() == 'deployed':
  42. return queryset.deployed()
  43. else:
  44. return queryset
  45. @admin.register(Item)
  46. class ItemAdmin(admin.ModelAdmin):
  47. list_display = (
  48. 'designation', 'type', 'mac_address', 'serial', 'owner',
  49. 'buy_date', 'deployed', 'is_available')
  50. list_filter = (
  51. AvailabilityFilter, 'type__name', 'storage',
  52. 'buy_date', OwnerFilter)
  53. search_fields = (
  54. 'designation', 'mac_address', 'serial',
  55. 'owner__email', 'owner__nickname',
  56. 'owner__first_name', 'owner__last_name')
  57. save_as = True
  58. actions = ['give_back']
  59. form = autocomplete_light.modelform_factory(Loan, fields='__all__')
  60. def give_back(self, request, queryset):
  61. for item in queryset.filter(loans__loan_date_end=None):
  62. item.give_back()
  63. give_back.short_description = 'Rendre le matériel'
  64. class StatusFilter(admin.SimpleListFilter):
  65. title = 'Statut'
  66. parameter_name = 'status'
  67. def lookups(self, request, model_admin):
  68. return [
  69. ('all', 'Tout'),
  70. (None, 'En cours'),
  71. ('finished', 'Passés'),
  72. ]
  73. def choices(self, cl):
  74. for lookup, title in self.lookup_choices:
  75. yield {
  76. 'selected': self.value() == lookup,
  77. 'query_string': cl.get_query_string({
  78. self.parameter_name: lookup,
  79. }, []),
  80. 'display': title,
  81. }
  82. def queryset(self, request, queryset):
  83. v = self.value()
  84. if v in (None, 'running'):
  85. return queryset.running()
  86. elif v == 'finished':
  87. return queryset.finished()
  88. else:
  89. return queryset
  90. class BorrowerFilter(admin.SimpleListFilter):
  91. title = 'Adhérent emprunteur'
  92. parameter_name = 'user'
  93. def lookups(self, request, model_admin):
  94. users = set()
  95. for loan in model_admin.get_queryset(request):
  96. users.add((loan.user.pk, loan.user))
  97. return users
  98. def queryset(self, request, queryset):
  99. if self.value():
  100. return queryset.filter(user=self.value())
  101. else:
  102. return queryset
  103. class ItemChoiceField(ModelChoiceField):
  104. # On surcharge cette méthode pour afficher mac et n° de série dans le menu
  105. # déroulant de sélection d'un objet dans la création d'un prêt.
  106. def label_from_instance(self, obj):
  107. return obj.designation + ' ' + obj.get_mac_and_serial()
  108. @admin.register(Loan)
  109. class LoanAdmin(admin.ModelAdmin):
  110. list_display = ('item', 'get_mac_and_serial', 'user', 'loan_date', 'loan_date_end')
  111. list_filter = (StatusFilter, BorrowerFilter, 'item__designation')
  112. search_fields = (
  113. 'item__designation',
  114. 'user__nickname', 'user__username',
  115. 'user__first_name', 'user__last_name', )
  116. actions = ['end_loan']
  117. def end_loan(self, request, queryset):
  118. queryset.filter(loan_date_end=None).update(
  119. loan_date_end=datetime.now())
  120. end_loan.short_description = 'Mettre fin au prêt'
  121. form = autocomplete_light.modelform_factory(Loan, fields='__all__')
  122. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  123. if db_field.name == 'item':
  124. kwargs['queryset'] = Item.objects.all()
  125. return ItemChoiceField(**kwargs)
  126. else:
  127. return super(LoanAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
  128. @admin.register(Storage)
  129. class StorageAdmin(admin.ModelAdmin):
  130. list_display = ('name', 'truncated_notes', 'items_count')
  131. def truncated_notes(self, obj):
  132. if len(obj.notes) > 50:
  133. return '{}…'.format(obj.notes[:50])
  134. else:
  135. return obj.notes
  136. truncated_notes.short_description = 'notes'
  137. class LoanInline(admin.TabularInline):
  138. model = Loan
  139. extra = 0
  140. exclude = ('notes',)
  141. readonly_fields = ('item', 'get_mac_and_serial', 'loan_date', 'loan_date_end', 'is_running')
  142. show_change_link = True
  143. def get_queryset(self, request):
  144. qs = super(LoanInline, self).get_queryset(request)
  145. return qs.order_by('-loan_date_end')
  146. def has_add_permission(self, request, obj=None):
  147. return False
  148. def has_delete_permission(self, request, obj=None):
  149. return False
  150. class MemberAdmin(coin.members.admin.MemberAdmin):
  151. inlines = coin.members.admin.MemberAdmin.inlines + [LoanInline]
  152. admin.site.unregister(coin.members.admin.Member)
  153. admin.site.register(coin.members.admin.Member, MemberAdmin)