context_processors.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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(
  39. itertools.chain.from_iterable(
  40. connections[x].queries for x in connections
  41. )
  42. ),
  43. list,
  44. )
  45. return context_extras
  46. def i18n(request):
  47. from django.utils import translation
  48. return {
  49. "LANGUAGES": settings.LANGUAGES,
  50. "LANGUAGE_CODE": translation.get_language(),
  51. "LANGUAGE_BIDI": translation.get_language_bidi(),
  52. }
  53. def tz(request):
  54. from django.utils import timezone
  55. return {"TIME_ZONE": timezone.get_current_timezone_name()}
  56. def static(request):
  57. """
  58. Add static-related context variables to the context.
  59. """
  60. return {"STATIC_URL": settings.STATIC_URL}
  61. def media(request):
  62. """
  63. Add media-related context variables to the context.
  64. """
  65. return {"MEDIA_URL": settings.MEDIA_URL}
  66. def request(request):
  67. return {"request": request}