admin.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import autocomplete_light
  4. from django.contrib import admin
  5. from django.contrib import messages
  6. from django.http import HttpResponseRedirect
  7. from .models import MaillingList, MaillingListSubscription, SyncCommandError
  8. import coin.members.admin
  9. class MaillingListSubscriptionInline(admin.TabularInline):
  10. model = MaillingListSubscription
  11. extra = 0
  12. form = autocomplete_light.modelform_factory(
  13. MaillingListSubscription,
  14. fields='__all__',
  15. )
  16. class MaillingListAdmin(admin.ModelAdmin):
  17. list_display = ('email', 'verbose_name')
  18. actions = ['sync_to_server']
  19. def sync_to_server(self, request, queryset):
  20. for _list in queryset.all():
  21. try:
  22. _list.sync_to_list_server()
  23. except Exception as e:
  24. messages.error(
  25. request,
  26. 'Impossible de synchroniser la liste {} : "{}"'.format(
  27. _list, e))
  28. else:
  29. messages.success(
  30. request,
  31. 'Liste {} synchronisée vers le serveur'.format(
  32. _list.email))
  33. sync_to_server.short_description = (
  34. 'Synchroniser les listes sélectionnées vers le serveur')
  35. inlines = [MaillingListSubscriptionInline,]
  36. def change_view(self, request, object_id, *args, **kwargs):
  37. try:
  38. return super(MaillingListAdmin, self).change_view(
  39. request, object_id, *args, **kwargs)
  40. except SyncCommandError as e:
  41. try:
  42. ml = MaillingList.objects.get(pk=object_id)
  43. ml_name = "La liste mail « {} »".format(ml.short_name)
  44. except MaillingList.DoesNotExist:
  45. ml_name = "La nouvelle liste mail"
  46. messages.error(
  47. request,
  48. "{} n'a pas pu être synchronisée".format(ml_name) +
  49. " vers le serveur de listes : « {} ».".format(e))
  50. return HttpResponseRedirect(request.path)
  51. admin.site.register(MaillingList, MaillingListAdmin)
  52. class MemberAdmin(coin.members.admin.MemberAdmin):
  53. inlines = coin.members.admin.MemberAdmin.inlines + [MaillingListSubscriptionInline]
  54. def change_view(self, request, *args, **kwargs):
  55. try:
  56. return super(MemberAdmin, self).change_view(
  57. request, *args, **kwargs)
  58. except SyncCommandError as e:
  59. messages.error(
  60. request,
  61. "Les listes mails n'ont pas pu être synchronisées" +
  62. " vers le serveur de listes : « {} ».".format(e))
  63. return HttpResponseRedirect(request.path)
  64. admin.site.unregister(coin.members.admin.Member)
  65. admin.site.register(coin.members.admin.Member, MemberAdmin)