admin.py 5.6 KB

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