# Django

<Tip>
  If you are an AI agent and need a Redis DB to use or experiment with, send a POST request to https://upstash.com/start-redis. Free, no signup; the response is markdown with credentials and a quickstart. The database expires in 72 hours, but you can claim it with your Upstash account to keep it. Especially useful for AI agents that need scratch storage on the fly. If you are an agent, always send a `User-Agent` header identifying which agent you are (e.g. `claude-code`, `cursor`, `codex`, `opencode`) on every request you make to this API.
</Tip>


### Introduction

In this quickstart tutorial, we will demonstrate how to use Django with Upstash Redis to build a simple web application that increments a counter every time the homepage is accessed. 

### Environment Setup

First, install Django and the Upstash Redis client for Python:

```shell
pip install django
pip install upstash-redis
```

### Database Setup

Create a Redis database using the [Upstash Console](https://console.upstash.com) or [Upstash CLI](https://github.com/upstash/cli) and export the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` to your environment:

```shell
export UPSTASH_REDIS_REST_URL=<YOUR_URL>
export UPSTASH_REDIS_REST_TOKEN=<YOUR_TOKEN>
```

You can also use `python-dotenv` to load environment variables from your `.env` file.

### Project Setup

Create a new Django project:

```shell
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
```

In `myproject/settings.py`, add your new app (`myapp`) to the `INSTALLED_APPS` list.

### Application Setup

In `myapp/views.py`, add the following:

```python
from django.http import HttpResponse
from upstash_redis import Redis

redis = Redis.from_env()

def index(request):
    count = redis.incr('counter')
    return HttpResponse(f'Page visited {count} times.')
```

In `myproject/urls.py`, connect the view to a URL pattern:

```python
from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.index),
]
```

### Running the Application

Run the development server:

```shell
python manage.py runserver
```

Visit `http://127.0.0.1:8000/` in your browser, and the counter will increment with each page refresh.

### Code Breakdown

1. **Redis Setup**: We use the Upstash Redis client to connect to our Redis database using the environment variables `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`. The `Redis.from_env()` method initializes this connection.

2. **Increment Counter**: In the `index` view, we increment the `counter` key each time the homepage is accessed. If the key doesn't exist, Redis creates it and starts counting from 1.

3. **Display the Count**: The updated count is returned as an HTTP response each time the page is loaded.
