You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mixins.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django.conf import settings
  2. from django.contrib.auth import authenticate, login as auth_login
  3. from django.contrib.sites.models import get_current_site
  4. from django.db.models import get_model
  5. from oscar.apps.customer.signals import user_registered
  6. from oscar.core.loading import get_class
  7. from oscar.core.compat import get_user_model
  8. User = get_user_model()
  9. CommunicationEventType = get_model('customer', 'CommunicationEventType')
  10. Dispatcher = get_class('customer.utils', 'Dispatcher')
  11. class PageTitleMixin(object):
  12. """
  13. Passes page_title and active_tab into context, which makes it quite useful
  14. for the accounts views.
  15. Dynamic page titles are possible by overriding get_page_title.
  16. """
  17. page_title = None
  18. active_tab = None
  19. # Use a method that can be overridden and customised
  20. def get_page_title(self):
  21. return self.page_title
  22. def get_context_data(self, **kwargs):
  23. ctx = super(PageTitleMixin, self).get_context_data(**kwargs)
  24. ctx.setdefault('page_title', self.get_page_title())
  25. ctx.setdefault('active_tab', self.active_tab)
  26. return ctx
  27. class RegisterUserMixin(object):
  28. communication_type_code = 'REGISTRATION'
  29. def register_user(self, form):
  30. """
  31. Create a user instance and send a new registration email (if configured
  32. to).
  33. """
  34. user = form.save()
  35. if getattr(settings, 'OSCAR_SEND_REGISTRATION_EMAIL', True):
  36. self.send_registration_email(user)
  37. # Raise signal
  38. user_registered.send_robust(sender=self, user=user)
  39. # We have to authenticate before login
  40. try:
  41. user = authenticate(
  42. username=user.email,
  43. password=form.cleaned_data['password1'])
  44. except User.MultipleObjectsReturned:
  45. # Handle race condition where the registration request is made
  46. # multiple times in quick succession. This leads to both requests
  47. # passing the uniqueness check and creating users (as the first one
  48. # hasn't committed when the second one runs the check). We retain
  49. # the first one and delete the dupes.
  50. users = User.objects.filter(email=user.email)
  51. user = users[0]
  52. for u in users[1:]:
  53. u.delete()
  54. auth_login(self.request, user)
  55. return user
  56. def send_registration_email(self, user):
  57. code = self.communication_type_code
  58. ctx = {'user': user,
  59. 'site': get_current_site(self.request)}
  60. messages = CommunicationEventType.objects.get_and_render(
  61. code, ctx)
  62. if messages and messages['body']:
  63. Dispatcher().dispatch_user_messages(user, messages)