Short answer
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.
- Django keeps cookies in response.cookies, not response.headers, so return the response through apply_cookies() or the visitor's price can change on every reload.
- cache_page stores the whole response keyed by URL, so it would hand one visitor's price and cookie to everyone; keep it off every view that renders a price.
- Async views need get_price_async() and await request.auser(); the sync client can block the event loop for up to 500 ms on a cold start.
- Leverprice verifies Stripe revenue for one-time Checkout Sessions; a subscription's first payment is reported with track_purchase() and shows as unverified.
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.
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.
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:
pip install leverprice stripeLEVERPRICE_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.
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.
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():
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)<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; 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 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_pageon 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_cookieas 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:
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)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 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 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 takes an ad-hoc price per checkout, and Leverprice verifies both one-time orders and a subscription's first payment there. Lemon Squeezy takes custom_price in cents, but it stops processing payments on March 31, 2027. 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".
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. 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). If most of your stack is async, the FastAPI guide 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:
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.
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 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).
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:
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, 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:
- Connect a test-mode Stripe endpoint in Leverprice; test and live data stay separate.
- 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.
- Click Buy. The amount on Stripe's page must equal the price you saw.
- Pay with a card from Stripe's testing docs, such as 4242 4242 4242 4242.
- Unset
LEVERPRICE_SECRET_KEYand 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 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 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, fetch the config once in the master so workers start with it:
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.