admin.py 5.4 KB

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