admin.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from __future__ import unicode_literals
  2. from django.contrib import admin
  3. from django.contrib.auth import get_user_model
  4. from mezzanine.accounts import get_profile_model, ProfileNotConfigured
  5. from mezzanine.core.admin import SitePermissionUserAdmin
  6. from mezzanine.conf import settings
  7. from mezzanine.utils.email import send_approved_mail, send_verification_mail
  8. User = get_user_model()
  9. user_list_display = SitePermissionUserAdmin.list_display
  10. user_list_display += ("is_active", "date_joined", "last_login")
  11. class UserProfileAdmin(SitePermissionUserAdmin):
  12. list_display = user_list_display
  13. def save_model(self, request, obj, form, change):
  14. """
  15. If the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``,
  16. send a notification email to the user being saved if their
  17. ``active`` status has changed to ``True``.
  18. If the ``ACCOUNTS_VERIFICATION_REQUIRED`` setting is ``True``,
  19. send a verification email instead.
  20. """
  21. must_send_verification_mail_after_save = False
  22. if change and settings.ACCOUNTS_APPROVAL_REQUIRED:
  23. if obj.is_active and not User.objects.get(id=obj.id).is_active:
  24. if settings.ACCOUNTS_VERIFICATION_REQUIRED:
  25. # Accounts verification requires an inactive account
  26. obj.is_active = False
  27. # The token generated by send_verification_mail()
  28. # must match the _saved_ User object,
  29. # so postpone send_verification_mail() until later
  30. must_send_verification_mail_after_save = True
  31. else:
  32. send_approved_mail(request, obj)
  33. super(UserProfileAdmin, self).save_model(request, obj, form, change)
  34. if must_send_verification_mail_after_save:
  35. user = User.objects.get(id=obj.id)
  36. send_verification_mail(request, user, "signup_verify")
  37. try:
  38. class ProfileInline(admin.StackedInline):
  39. model = get_profile_model()
  40. can_delete = False
  41. template = "admin/profile_inline.html"
  42. extra = 0
  43. def get_min_num(self, request, obj=None, **kwargs):
  44. """This causes profile forms to be shown when editing but hidden
  45. when creating. If min_num is fixed at 1, Django's initial user
  46. creation form fails if the profile model has a required field."""
  47. return 0 if obj is None else 1
  48. UserProfileAdmin.inlines += (ProfileInline,)
  49. except ProfileNotConfigured:
  50. pass
  51. if User in admin.site._registry:
  52. admin.site.unregister(User)
  53. admin.site.register(User, UserProfileAdmin)