admin.py 5.7 KB

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