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.

utils.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from __future__ import absolute_import # for import below
  2. import six
  3. import logging
  4. from django.utils.timezone import get_current_timezone, is_naive, make_aware
  5. from unidecode import unidecode
  6. from django.conf import settings
  7. from django.template.defaultfilters import date as date_filter
  8. def slugify(value):
  9. """
  10. Slugify a string (even if it contains non-ASCII chars)
  11. """
  12. # Re-map some strings to avoid important characters being stripped. Eg
  13. # remap 'c++' to 'cpp' otherwise it will become 'c'.
  14. if hasattr(settings, 'OSCAR_SLUG_MAP'):
  15. for k, v in settings.OSCAR_SLUG_MAP.items():
  16. value = value.replace(k, v)
  17. # Allow an alternative slugify function to be specified
  18. if hasattr(settings, 'OSCAR_SLUG_FUNCTION'):
  19. slugifier = settings.OSCAR_SLUG_FUNCTION
  20. else:
  21. from django.template import defaultfilters
  22. slugifier = defaultfilters.slugify
  23. # Use unidecode to convert non-ASCII strings to ASCII equivalents where
  24. # possible.
  25. value = slugifier(unidecode(six.text_type(value)))
  26. # Remove stopwords
  27. if hasattr(settings, 'OSCAR_SLUG_BLACKLIST'):
  28. for word in settings.OSCAR_SLUG_BLACKLIST:
  29. value = value.replace(word + '-', '')
  30. value = value.replace('-' + word, '')
  31. return value
  32. def compose(*functions):
  33. """
  34. Compose functions
  35. This is useful for combining decorators.
  36. """
  37. def _composed(*args):
  38. for fn in functions:
  39. try:
  40. args = fn(*args)
  41. except TypeError:
  42. # args must be scalar so we don't try to expand it
  43. args = fn(args)
  44. return args
  45. return _composed
  46. def format_datetime(dt, format=None):
  47. """
  48. Takes an instance of datetime, converts it to the current timezone and
  49. formats it as a string. Use this instead of
  50. django.core.templatefilters.date, which expects localtime.
  51. :param format: Common will be settings.DATETIME_FORMAT or
  52. settings.DATE_FORMAT, or the resp. shorthands
  53. ('DATETIME_FORMAT', 'DATE_FORMAT')
  54. """
  55. if is_naive(dt):
  56. localtime = make_aware(dt, get_current_timezone())
  57. logging.warning(
  58. "oscar.core.utils.format_datetime received native datetime")
  59. else:
  60. localtime = dt.astimezone(get_current_timezone())
  61. return date_filter(localtime, format)