context_processors.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from __future__ import unicode_literals
  2. from warnings import warn
  3. # Deprecated settings and their defaults.
  4. DEPRECATED = {}
  5. class TemplateSettings(dict):
  6. """
  7. Dict wrapper for template settings. This exists to enforce
  8. the restriction of settings in templates to those named in
  9. TEMPLATE_ACCESSIBLE_SETTINGS, and to warn about deprecated settings.
  10. Django's template system attempts a dict-style index lookup before an
  11. attribute lookup when resolving dot notation in template variables, so we
  12. use ``__getitem__()`` this as the primary way of getting at the settings.
  13. """
  14. def __init__(self, settings, allowed_settings, *args, **kwargs):
  15. super(TemplateSettings, self).__init__(*args, **kwargs)
  16. self.settings = settings
  17. self.allowed_settings = set(allowed_settings)
  18. def __getattr__(self, k):
  19. try:
  20. return self.__getitem__(k)
  21. except KeyError:
  22. raise AttributeError
  23. def __getitem__(self, k):
  24. if k not in self.allowed_settings:
  25. warn("%s is not in TEMPLATE_ACCESSIBLE_SETTINGS." % k)
  26. raise KeyError
  27. if k in DEPRECATED:
  28. warn("%s is deprecated. Please remove it from your templates." % k)
  29. try:
  30. return getattr(self.settings, k)
  31. except AttributeError:
  32. return super(TemplateSettings, self).__getitem__(k)
  33. def __setitem__(self, k, v):
  34. self.allowed_settings.add(k)
  35. super(TemplateSettings, self).__setitem__(k, v)
  36. def settings(request=None):
  37. """
  38. Add the settings object to the template context.
  39. """
  40. from mezzanine.conf import settings
  41. allowed_settings = settings.TEMPLATE_ACCESSIBLE_SETTINGS
  42. template_settings = TemplateSettings(settings, allowed_settings)
  43. template_settings.update(DEPRECATED)
  44. # This is basically the same as the old ADMIN_MEDIA_PREFIX setting,
  45. # we just use it in a few spots in the admin to optionally load a
  46. # file from either grappelli or Django admin if grappelli isn't
  47. # installed. We don't call it ADMIN_MEDIA_PREFIX in order to avoid
  48. # any confusion.
  49. admin_prefix = "grappelli/" if settings.GRAPPELLI_INSTALLED else "admin/"
  50. template_settings["MEZZANINE_ADMIN_PREFIX"] = admin_prefix
  51. return {"settings": template_settings}