# How to A/B test prices in Django

Source: https://leverprice.com/guides/django
Updated: 2026-11-17

> Install the leverprice package and create one client per process. In the view that renders the price, call get_price() and return the response through apply_cookies(). In the checkout view, call it again and pass quote.price and the whole quote.metadata to Stripe Checkout. Connect Stripe's webhook to Leverprice, and never cache the pricing view.

A Django price test lives in two views and can be ruined by one decorator. The pricing view asks Leverprice which price this visitor gets; the checkout view asks again and charges exactly that amount in Stripe Checkout. Put `cache_page` on the pricing view and the first visitor's price, cookie included, gets served to everyone who comes after.

The code below targets Django 6.1, stripe-python 17 and the `leverprice` package for Python 3.9+.

## How does price testing work in a Django app?

Every price decision happens on your server. `get_price()` reads the visitor's `__pp` cookie and user agent from the `HttpRequest`, picks their price from a signed config the SDK keeps in memory, checks it against bounds you set in code and returns a quote: `price` in minor units (2900 is $29.00), `currency`, a signed `metadata` dict and a list of Set-Cookie values. No Leverprice JavaScript runs in the browser.

*Figure: Diagram: a visitor requests the pricing page, your server asks the SDK for a price, the checkout charges that price, and Leverprice moves traffic toward the best earner. The price is decided on your server twice: once for the page and once for the checkout.*

The checkout view repeats the call. The signed cookie makes the second answer match the first, and `quote.metadata` travels into the Checkout Session so the payment can be tied to the price the visitor saw. Stripe then reports the payment to Leverprice in a signed webhook, and the engine shifts traffic toward the price that earns the most per visitor. If you want the reasoning behind doing this on the server instead of swapping prices in JavaScript, read [why price tests belong on the server](https://leverprice.com/blog/server-side-price-testing).

## How do I install the SDK in Django?

Install both libraries and put the keys in the environment your Django process reads. Use test keys on your machine:

```bash
pip install leverprice stripe
```

```bash title=".env"
LEVERPRICE_SECRET_KEY=pp_sk_test_...
STRIPE_SECRET_KEY=sk_test_...
```

Create one client per process in a module of its own. Views import it; nothing creates a client per request.

```python title="pricing/leverprice.py"
import os

from leverprice import Leverprice

leverprice = Leverprice(
    secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
    products={
        # Guardrails in minor units: a price outside them is never returned.
        "pro": {"currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900},
    },
)
```

`fallback_price` is what visitors pay whenever Leverprice cannot answer: no key, `LEVERPRICE_DISABLED=1`, or no signed config within 500 ms. `get_price()` never raises for those reasons, only for a product key missing from `products`. `min_price` and `max_price` are enforced on your server, so a config that tries to charge outside them gets your fallback instead. Every option is listed in the [SDK documentation](https://leverprice.com/docs).

## How do I show the tested price in a Django view?

Call `get_price()` in the view that renders the price and return the response through `apply_cookies()`:

```python title="pricing/views.py"
from django.shortcuts import render
from leverprice import apply_cookies

from .leverprice import leverprice


def pricing(request):
    user_id = request.user.pk if request.user.is_authenticated else None
    quote = leverprice.get_price("pro", request, user_id=user_id)
    context = {"quote": quote, "amount": quote.price / 100}
    return apply_cookies(render(request, "pricing/pricing.html", context), quote)
```

```html title="pricing/templates/pricing/pricing.html"
<p class="price">{{ amount|floatformat:"-2" }} {{ quote.currency|upper }}</p>
<form method="post" action="{% url 'checkout' %}">
  {% csrf_token %}
  <button type="submit">Buy Pro</button>
</form>
```

Return the response through `apply_cookies()`, never around it. Django's `response.headers` covers every header except Set-Cookie, per the [request and response reference](https://docs.djangoproject.com/en/6.1/ref/request-response/#django.http.HttpResponse.headers); cookies live in `response.cookies`, and `apply_cookies()` loads each value there unchanged. Without it the browser never keeps the `__pp` cookie, so every reload can land on a different price.

`user_id` puts a signed-in customer in the same bucket on every device, and only an HMAC of it leaves your server. Pass it the same way everywhere you price the product. `floatformat:"-2"` prints 29 for 2900 and 29.50 for 2950.

While you build, print `quote.reason`. `"experiment"` means the visitor is in a running test, `"base_price"` means no test is running, and `"disabled"` or `"no_config"` mean the fallback kicked in.

## Why does cache_page break a Django price test?

Because it stores the whole response, Set-Cookie included, under a key built from the URL. Django's [cache documentation](https://docs.djangoproject.com/en/6.1/topics/cache/#the-per-view-cache) says `cache_page` "does not automatically vary by authentication, sessions, cookies, or other request-specific state", and as a view decorator it caches before response middleware runs. The first visitor's price and signed cookie would be replayed to everyone until the entry expires: every reader becomes the same visitor, sees the same price, and the test stops learning.

The rules for a Django project:

- Never put `cache_page` on a view that renders a tested price. The checkout view is a POST, and Django's cache middleware only stores GET and HEAD responses.
- If you run the per-site cache middleware, decorate the pricing view with `@never_cache`, which the same page documents as the way to keep a response out of browser and shared caches.
- If a CDN caches your HTML, exclude the pricing URL there as well.
- Cache the expensive parts with `{% cache %}` template fragments that do not contain the price.
- Don't reach for `vary_on_cookie` as a workaround: it turns the cache into one entry per visitor, which saves almost nothing.

## How do I charge the same price with Stripe Checkout?

Price the checkout on the server again and ignore any amount the browser sends. Stripe's `price_data` takes the amount inline, so you never create a Stripe Price per tested price:

```python title="pricing/views.py"
import os

from django.shortcuts import redirect
from django.urls import reverse
from django.views.decorators.http import require_POST
from leverprice import apply_cookies
from stripe import StripeClient

from .leverprice import leverprice

stripe_client = StripeClient(os.environ["STRIPE_SECRET_KEY"])


@require_POST
def checkout(request):
    user_id = request.user.pk if request.user.is_authenticated else None
    quote = leverprice.get_price("pro", request, user_id=user_id)
    session = stripe_client.v1.checkout.sessions.create({
        "mode": "payment",
        "line_items": [{
            "quantity": 1,
            "price_data": {
                "currency": quote.currency,
                "unit_amount": quote.price,
                "product_data": {"name": "Pro"},
            },
        }],
        "metadata": quote.metadata,  # signed attribution: pass it whole
        "payment_intent_data": {"metadata": quote.metadata},
        "success_url": request.build_absolute_uri("/thanks/"),
        "cancel_url": request.build_absolute_uri(reverse("pricing")),
    })
    return apply_cookies(redirect(session.url), quote)
```

```python title="pricing/urls.py"
from django.urls import path

from . import views

urlpatterns = [
    path("pricing/", views.pricing, name="pricing"),
    path("checkout/", views.checkout, name="checkout"),
]
```

`quote.metadata` holds `pp_exp`, `pp_var`, `pp_vid` and `pp_sig`. The signature covers all four, so pass the dict whole and never pick keys out of it. The form posts to your own URL, so it keeps `{% csrf_token %}`; Django's [CSRF guide](https://docs.djangoproject.com/en/6.1/howto/csrf/) asks for the tag on internal POST forms, and the checkout view needs no exemption.

Selling a subscription instead? Set `"mode": "subscription"`, add `"recurring": {"interval": "month"}` inside `price_data`, and move the metadata copy from `payment_intent_data` to `subscription_data`, since the [Checkout Session API](https://docs.stripe.com/api/checkout/sessions/create) accepts `payment_intent_data` only in payment mode. Leverprice's Stripe verification covers one-time payments, so a subscription's first payment has to be reported with `track_purchase()` from your own webhook view (shown below) and appears as unverified. Renewals never count toward a test.

The same two rules, charge `quote.price` and pass `quote.metadata` whole, carry over to the other providers. [Polar](https://leverprice.com/integrations/polar) takes an ad-hoc price per checkout, and Leverprice verifies both one-time orders and a subscription's first payment there. [Lemon Squeezy](https://leverprice.com/integrations/lemon-squeezy) takes `custom_price` in cents, but it [stops processing payments on March 31, 2027](https://www.lemonsqueezy.com/blog/saying-goodbye-to-lemon-squeezy). [Dodo Payments](https://leverprice.com/integrations/dodo-payments) accepts a custom amount only on pay-what-you-want products, and Leverprice verifies its one-time payments.

## Can I use async views?

Yes, if the whole path is async. A sync `get_price()` inside `async def` blocks the event loop for up to 500 ms while a cold process fetches its config, and `request.user` is not safe to touch there; the reference documents `request.auser()` as the variant that "works in async contexts".

```python title="pricing/views.py"
from django.http import JsonResponse
from leverprice import apply_cookies

from .leverprice import leverprice


async def price_json(request):
    user = await request.auser()
    quote = await leverprice.get_price_async(
        "pro", request, user_id=user.pk if user.is_authenticated else None
    )
    return apply_cookies(JsonResponse({"price": quote.price, "currency": quote.currency}), quote)
```

For an async checkout, call `await stripe_client.v1.checkout.sessions.create_async({...})`. stripe-python sends async requests through httpx, which `pip install "stripe[async]"` adds, per the [stripe-python README](https://github.com/stripe/stripe-python). Django runs async views under WSGI too, in a one-off event loop with a small cost per request, so they pay off only on an ASGI server ([async support](https://docs.djangoproject.com/en/6.1/topics/async/)). If most of your stack is async, the [FastAPI guide](https://leverprice.com/guides/fastapi) covers the same traps from the other side.

## Can I show a different price per country?

Yes. With regional prices on in the dashboard, each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), in the currency it is charged in. Example: a visitor from India sees ₹999 where a visitor from the US sees $29. Your code decides where the country comes from and which prices it lets through:

```python title="pricing/leverprice.py"
leverprice = Leverprice(
    secret_key=os.environ.get("LEVERPRICE_SECRET_KEY"),
    country_header="cf-ipcountry",  # set by Cloudflare; on Vercel: x-vercel-ip-country
    products={
        "pro": {
            "currency": "usd", "fallback_price": 2900, "min_price": 1900, "max_price": 4900,
            "regional": {  # currencies you accept, each with hard bounds
                "usd": {"min_price": 800, "max_price": 4900},
                "eur": {"min_price": 1100, "max_price": 6000},
                "inr": {"min_price": 48000, "max_price": 230000},
            },
        },
    },
)
```

`country_header` has no default on purpose: a header visitors can send themselves would let them pick their own price, so name one your CDN overwrites. Pass the plain header name; under Django the SDK finds `HTTP_CF_IPCOUNTRY` for you. A currency missing from `regional`, or a price outside its bounds, falls back to the standard price, and so do bots and visitors whose country is unknown.

The checkout above already passes `quote.currency`, which is the other half of the job, so make sure your Stripe account can charge in every listed currency. When you format the price, use the currency's own decimals: JPY has none, per Stripe's list of [zero-decimal currencies](https://docs.stripe.com/currencies#zero-decimal).

## How does Leverprice verify revenue from Stripe?

Stripe reports to Leverprice directly. In the Leverprice dashboard, open Payments and connect Stripe to get an endpoint URL. In Stripe, add that URL as a webhook endpoint subscribed to `checkout.session.completed`, `checkout.session.async_payment_succeeded` and `charge.refunded`, then paste the endpoint's signing secret (`whsec_…`) back into Leverprice.

A signing secret can confirm events but cannot move money, so never paste an API key there. Refunds reduce the tested price's revenue on their own. The [Stripe integration page](https://leverprice.com/integrations/stripe) covers the details.

That path needs no Django code. An existing Stripe webhook view keeps working, because Stripe delivers each event to every endpoint subscribed to it ([up to 16 per account](https://docs.stripe.com/webhooks)).

Your own handler matters in two cases: you cannot add an endpoint, or you sell subscriptions. Revenue reported this way is labeled unverified and never overrides a verified purchase:

```python title="pricing/webhooks.py"
import os

import stripe
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .leverprice import leverprice
from .views import stripe_client

PAID = {"checkout.session.completed", "checkout.session.async_payment_succeeded"}


@csrf_exempt  # Stripe cannot send a CSRF token
@require_POST
def stripe_webhook(request):
    try:
        event = stripe_client.construct_event(
            request.body, request.headers.get("Stripe-Signature"), os.environ["STRIPE_WEBHOOK_SECRET"]
        )
    except (ValueError, stripe.SignatureVerificationError):
        return HttpResponseBadRequest()
    if event.type in PAID and event.data.object.payment_status == "paid":
        session = event.data.object
        tax = session.total_details.amount_tax if session.total_details else 0
        leverprice.track_purchase(
            provider="stripe",
            order_id=session.payment_intent or session.invoice,  # invoice: subscription mode
            amount=session.amount_total - tax,
            currency=session.currency,
            metadata=session.metadata.to_dict(),
            timestamp=event.created,
        )
    return HttpResponse()
```

Verify against `request.body`, the raw bytes Stripe signed, before parsing anything. Note `.to_dict()`: since [stripe-python 15.0.0](https://github.com/stripe/stripe-python/blob/master/CHANGELOG.md), Stripe objects are no longer dicts, and a `StripeObject` passed as `metadata` reaches the SDK with no readable attribution.

## How do I test a Django price test locally?

Run everything with test keys and walk through it in a browser:

1. Connect a test-mode Stripe endpoint in Leverprice; test and live data stay separate.
2. Open the pricing page and note the price. Reload: it must not change. A private window is a new visitor and may get another price.
3. Click Buy. The amount on Stripe's page must equal the price you saw.
4. Pay with a card from Stripe's [testing docs](https://docs.stripe.com/testing), such as 4242 4242 4242 4242.
5. Unset `LEVERPRICE_SECRET_KEY` and reload. You should get the fallback price with reason `"disabled"`, and nothing should crash.

Two local surprises. `runserver` serves plain HTTP and the cookie is `Secure` by default; [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie) documents an exception only for localhost, so on a LAN address (testing from a phone) pass `cookie_secure=False` while `DEBUG` is on. And curl always gets the standard price, because command-line clients count as bots.

## What changes when I deploy?

Swap in `pp_sk_live_…` and your live Stripe key, and connect the live-mode Stripe endpoint in Leverprice; it has its own signing secret. Behind a proxy that terminates TLS, set [`SECURE_PROXY_SSL_HEADER`](https://docs.djangoproject.com/en/6.1/ref/settings/#secure-proxy-ssl-header) so `build_absolute_uri()` hands Stripe https URLs.

The client is thread-safe and handles forking servers: each gunicorn worker starts with fresh threads and an empty event queue. With [`--preload`](https://gunicorn.org/reference/settings/#preload_app), fetch the config once in the master so workers start with it:

```python title="config/wsgi.py"
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
application = get_wsgi_application()

from pricing.leverprice import leverprice  # noqa: E402

leverprice.preload()
```

Keep `LEVERPRICE_DISABLED=1` in your runbook: set it, restart, and every visitor gets your fallback price with no calls to Leverprice. Health checks and uptime monitors get the standard price and are never enrolled, so they don't pollute the test.

## What breaks most often?

| Symptom | Likely cause | Fix |
|---|---|---|
| Price changes on reload | Set-Cookie never reaches the browser | Return the response through `apply_cookies()` |
| Everyone sees one price | `cache_page`, the per-site cache or a CDN caches the page | Remove it; add `@never_cache` to the pricing view |
| `reason` is `"disabled"` in production | The key is missing in the gunicorn process, or `LEVERPRICE_DISABLED` is set | Check the service's environment, not your shell |
| `reason` is `"bot"` in tests | curl, python-requests and headless Chrome count as bots | Test in a real browser, or pass `bot=False` in automated tests |
| 403 on checkout | The form lacks `{% csrf_token %}` | Add the tag; don't exempt the checkout view |
| `SynchronousOnlyOperation` in an async view | `request.user` touched in async code | Use `await request.auser()` and `get_price_async()` |
| Purchases from your own handler have no attribution | A `StripeObject` passed as `metadata` | Pass `session.metadata.to_dict()` |

## Frequently asked questions

### Does this work with Django REST Framework?

Yes. Pass the DRF `Request` to `get_price()`: it forwards attribute access, headers included, to Django's request. DRF's `Response` is a Django response, so `apply_cookies()` works on it unchanged.

### Can the pricing page stay cached if the price loads with JavaScript?

Yes. Cache the HTML, fetch the price from an uncached JSON view like `price_json` above, and keep pricing the checkout on the server. Exposures are counted when that view runs, which is right when the fetch happens on page load.

### What happens when the test ends?

You lock in the winner in the dashboard, and it is live for every visitor in about a second. `get_price()` keeps working unchanged, so there is nothing to deploy.

### How long does a Django price test take?

As long as it takes to collect enough paid orders; the framework doesn't change that. The engine counts only visitors older than 30 minutes, so a fresh deploy looks quiet for its first half hour. For realistic timelines at your sales volume, see [how long a price test should run](https://leverprice.com/blog/how-long-should-a-price-test-run).
