{
  "schema_version": 2,
  "id": "integrate/django",
  "title": "Redis with Django",
  "url": "https://redis.io/docs/latest/integrate/django/",
  "summary": "Use Redis as the cache, session store, and channel layer for a Django application.",
  "tags": [
    "docs",
    "integrate",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-11-17T15:08:14Z",
  "children": [],
  "page_type": "content",
  "content_hash": "c1fc8ba4cc2363805c0079b6468f7a978535895a658e1f1d84d84a852f531256",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "[Django](https://www.djangoproject.com/) is a Python web framework. You can use Redis\nwith Django as the [cache](#cache-data), the [session store](#store-sessions), and the\n[channel layer](#broadcast-messages-with-channels) that connects WebSocket clients\nthrough [Django Channels](https://channels.readthedocs.io/)."
    },
    {
      "id": "requirements",
      "title": "Requirements",
      "role": "content",
      "text": "| Dependency | Notes |\n|------------|-------|\n| Django | 4.0 or later for the built-in Redis cache backend |\n| [redis-py](https://redis.io/docs/latest/develop/clients/redis-py) | Required by both cache backends |\n| [django-redis](https://github.com/jazzband/django-redis) | Optional third-party cache backend |\n| [channels](https://channels.readthedocs.io/) and [channels-redis](https://github.com/django/channels_redis) | Required for the channel layer |\n\nThe examples on this page were run with Django 6.1, django-redis 7.0, Channels 4.3, and\nchannels-redis 4.3 against Redis 7.2.\n\nYou also need a running Redis server. You can run one locally with\n[Redis Open Source](https://redis.io/docs/latest/operate/oss_and_stack/install/archive/install-redis),\nuse [Docker](https://hub.docker.com/_/redis), or connect to\n[Redis Cloud](https://redis.io/cloud/)."
    },
    {
      "id": "cache-data",
      "title": "Cache data",
      "role": "content",
      "text": "Django has a built-in Redis cache backend, and the `django-redis` package provides a\nsecond one. Both implement Django's standard [cache API](https://docs.djangoproject.com/en/stable/topics/cache/),\nso the code that uses the cache is the same with either."
    },
    {
      "id": "use-the-built-in-backend",
      "title": "Use the built-in backend",
      "role": "content",
      "text": "Install redis-py, then point the `CACHES` setting at your server in `settings.py`:\n\n[code example]\n\n[code example]"
    },
    {
      "id": "use-django-redis",
      "title": "Use django-redis",
      "role": "content",
      "text": "`django-redis` adds methods that the standard cache API doesn't have. Install it, then\nuse its backend:\n\n[code example]\n\n[code example]\n\nWith `django-redis`, the cache object also provides:\n\n| Method | Use |\n|--------|-----|\n| `cache.ttl(key)` | Returns the remaining time to live (TTL) of a key in seconds. |\n| `cache.delete_pattern(\"user:*\")` | Deletes every key that matches a glob pattern and returns the number deleted. |\n| `cache.lock(name, timeout=5)` | Returns a lock that you use with `with`, to coordinate work across processes. |"
    },
    {
      "id": "read-and-write-the-cache",
      "title": "Read and write the cache",
      "role": "content",
      "text": "Use `get_or_set()` for the [cache-aside](https://redis.io/docs/latest/develop/use-cases/cache-aside)\npattern. It returns the cached value, or calls your function and stores the result on\na miss:\n\n[code example]\n\nDjango stores each entry under a key of the form `<prefix>:<version>:<key>`. With the\n`myapp` prefix and the default version, the entry above is stored as `myapp:1:book:1`.\nValues are serialized with `pickle`, so Redis stores them as strings, and the `timeout`\nbecomes the key's TTL."
    },
    {
      "id": "store-sessions",
      "title": "Store sessions",
      "role": "content",
      "text": "Django can keep sessions in the cache, so with Redis as the cache they live in Redis.\nSet the session engine in `settings.py`:\n\n[code example]\n\nDjango then stores each session as a cache entry such as\n`myapp:1:django.contrib.sessions.cache<session-key>`, with a TTL equal to\n`SESSION_COOKIE_AGE`.\n\n> [!NOTE]\n> A cache-based session lives only in Redis. If Redis evicts the key or loses its data,\n> the user's session ends. See the\n> [Django session documentation](https://docs.djangoproject.com/en/stable/topics/http/sessions/#using-cached-sessions)\n> for the `cached_db` engine, which also writes sessions to your database.\n\nSee the [session store use case](https://redis.io/docs/latest/develop/use-cases/session-store)\nfor more about this pattern."
    },
    {
      "id": "broadcast-messages-with-channels",
      "title": "Broadcast messages with Channels",
      "role": "content",
      "text": "Django Channels adds WebSocket support to Django. Its Redis channel layer lets\nconsumers running in different processes send messages to each other and to groups of\nclients. Install the packages:\n\n[code example]\n\nConfigure the channel layer in `settings.py`:\n\n[code example]\n\nThe following consumer adds each connection to a group named after the chat room, and\nrelays every message it receives to the whole group:\n\n[code example]\n\nWith two clients connected to the same room, a message sent by one arrives at both.\nChannels keeps the group membership in Redis, under a key such as `asgi:group:<room>`.\nSee the [pub/sub use case](https://redis.io/docs/latest/develop/use-cases/pub-sub) for other\nways to broadcast messages with Redis."
    },
    {
      "id": "more-information",
      "title": "More information",
      "role": "content",
      "text": "- [Django cache framework](https://docs.djangoproject.com/en/stable/topics/cache/)\n- [django-redis documentation](https://github.com/jazzband/django-redis)\n- [Channels documentation](https://channels.readthedocs.io/)"
    }
  ],
  "examples": [
    {
      "id": "use-the-built-in-backend-ex0",
      "language": "bash",
      "code": "pip install redis",
      "section_id": "use-the-built-in-backend"
    },
    {
      "id": "use-the-built-in-backend-ex1",
      "language": "python",
      "code": "CACHES = {\n    \"default\": {\n        \"BACKEND\": \"django.core.cache.backends.redis.RedisCache\",\n        \"LOCATION\": \"redis://<your-redis-host>:6379\",\n        \"TIMEOUT\": 300,\n        \"KEY_PREFIX\": \"myapp\",\n    }\n}",
      "section_id": "use-the-built-in-backend"
    },
    {
      "id": "use-django-redis-ex0",
      "language": "bash",
      "code": "pip install django-redis",
      "section_id": "use-django-redis"
    },
    {
      "id": "use-django-redis-ex1",
      "language": "python",
      "code": "CACHES = {\n    \"default\": {\n        \"BACKEND\": \"django_redis.cache.RedisCache\",\n        \"LOCATION\": \"redis://<your-redis-host>:6379/0\",\n        \"OPTIONS\": {\"CLIENT_CLASS\": \"django_redis.client.DefaultClient\"},\n        \"KEY_PREFIX\": \"myapp\",\n    }\n}",
      "section_id": "use-django-redis"
    },
    {
      "id": "read-and-write-the-cache-ex0",
      "language": "python",
      "code": "from django.core.cache import cache\n\nbook = cache.get_or_set(\"book:1\", load_book_from_database, timeout=30)",
      "section_id": "read-and-write-the-cache"
    },
    {
      "id": "store-sessions-ex0",
      "language": "python",
      "code": "SESSION_ENGINE = \"django.contrib.sessions.backends.cache\"\nSESSION_CACHE_ALIAS = \"default\"\nSESSION_COOKIE_AGE = 900  # seconds",
      "section_id": "store-sessions"
    },
    {
      "id": "broadcast-messages-with-channels-ex0",
      "language": "bash",
      "code": "pip install channels channels-redis",
      "section_id": "broadcast-messages-with-channels"
    },
    {
      "id": "broadcast-messages-with-channels-ex1",
      "language": "python",
      "code": "CHANNEL_LAYERS = {\n    \"default\": {\n        \"BACKEND\": \"channels_redis.core.RedisChannelLayer\",\n        \"CONFIG\": {\"hosts\": [(\"<your-redis-host>\", 6379)]},\n    }\n}",
      "section_id": "broadcast-messages-with-channels"
    },
    {
      "id": "broadcast-messages-with-channels-ex2",
      "language": "python",
      "code": "from channels.generic.websocket import AsyncWebsocketConsumer\n\nclass ChatConsumer(AsyncWebsocketConsumer):\n    async def connect(self):\n        self.room = self.scope[\"url_route\"][\"kwargs\"][\"room\"]\n        await self.channel_layer.group_add(self.room, self.channel_name)\n        await self.accept()\n\n    async def disconnect(self, code):\n        await self.channel_layer.group_discard(self.room, self.channel_name)\n\n    async def receive(self, text_data):\n        await self.channel_layer.group_send(\n            self.room, {\"type\": \"chat.message\", \"text\": text_data}\n        )\n\n    async def chat_message(self, event):\n        await self.send(text_data=event[\"text\"])",
      "section_id": "broadcast-messages-with-channels"
    }
  ]
}
