Dragonfly Cloud is now available in the AWS Marketplace - learn more

Question: How to Use Redis with Django?

Answer

To use Redis with Django, follow the step-by-step instructions below:

  1. Install the necessary packages: You'll need the django-redis package for Django integration and redis package as a client library.

    pip install django-redis redis
  2. Configure your Django project:

    In your Django settings.py file, add the following configuration to set up django-redis as a cache backend:

    CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', # Change this according to your Redis server's URL & port 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } }

    Replace 'redis://127.0.0.1:6379/1' with your Redis server's URL if it isn't running on your local machine or uses a different port.

Ensure that the Django application can access the Redis server at the provided location; incorrect configuration may lead to errors such as django.core.exceptions.ImproperlyConfigured.

  1. Use Redis within views or models:

    You can now utilize Redis in any Django view, model, or other components to cache data or perform various operations. Here's how you can use Redis cache in a view:

    from django.core.cache import cache def my_view(request): # Set a value into the cache cache.set('my_key', 'my_value', 300) # Cache for 300 seconds # Get a value from the cache my_value = cache.get('my_key') # Other cache operations are also available, such as 'add', 'get_or_set', 'incr', 'decr', etc. ...
  2. (Optional) Use Redis as a session storage backend:

    If you wish to use Redis for Django session management, update your settings.py file with the following configuration:

    SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" # Use the 'default' cache alias defined earlier

Make sure to restart your Django server after updating your settings for these changes to take effect.

Now, you have successfully integrated Redis with Django and can use it as a cache and session storage. Remember to handle all exceptions properly in your code to avoid errors like "django.core.exceptions.ImproperlyConfigured".

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost