admin.py 5.7 KB

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