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.

context_processors.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. A set of request processors that return dictionaries to be merged into a
  3. template context. Each function takes the request object as its only parameter
  4. and returns a dictionary to add to the context.
  5. These are referenced from the 'context_processors' option of the configuration
  6. of a DjangoTemplates backend and used by RequestContext.
  7. """
  8. import itertools
  9. from django.conf import settings
  10. from django.middleware.csrf import get_token
  11. from django.utils.functional import SimpleLazyObject, lazy
  12. def csrf(request):
  13. """
  14. Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
  15. it has not been provided by either a view decorator or the middleware
  16. """
  17. def _get_val():
  18. token = get_token(request)
  19. if token is None:
  20. # In order to be able to provide debugging info in the
  21. # case of misconfiguration, we use a sentinel value
  22. # instead of returning an empty dict.
  23. return 'NOTPROVIDED'
  24. else:
  25. return token
  26. return {'csrf_token': SimpleLazyObject(_get_val)}
  27. def debug(request):
  28. """
  29. Return context variables helpful for debugging.
  30. """
  31. context_extras = {}
  32. if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
  33. context_extras['debug'] = True
  34. from django.db import connections
  35. # Return a lazy reference that computes connection.queries on access,
  36. # to ensure it contains queries triggered after this function runs.
  37. context_extras['sql_queries'] = lazy(
  38. lambda: list(itertools.chain.from_iterable(connections[x].queries for x in connections)),
  39. list
  40. )
  41. return context_extras
  42. def i18n(request):
  43. from django.utils import translation
  44. return {
  45. 'LANGUAGES': settings.LANGUAGES,
  46. 'LANGUAGE_CODE': translation.get_language(),
  47. 'LANGUAGE_BIDI': translation.get_language_bidi(),
  48. }
  49. def tz(request):
  50. from django.utils import timezone
  51. return {'TIME_ZONE': timezone.get_current_timezone_name()}
  52. def static(request):
  53. """
  54. Add static-related context variables to the context.
  55. """
  56. return {'STATIC_URL': settings.STATIC_URL}
  57. def media(request):
  58. """
  59. Add media-related context variables to the context.
  60. """
  61. return {'MEDIA_URL': settings.MEDIA_URL}
  62. def request(request):
  63. return {'request': request}