# Clickwrap agreement in Django

> Clickwrap agreement in Django with working code: a requests client, three views, the signup template, the model and a signed webhook. No package to install.

Source: https://esigncomply.com/guides/django-clickwrap

Stack guide · Django

One small Django app adds a terms and privacy checkbox to your signup, calls the Esign Comply API with `requests`, and creates the user only after the acceptance is confirmed as a sealed record.

[Get started](https://esigncomply.com/signup) · [Read the quickstart](https://esigncomply.com/docs/quickstart)

Free plan: 10 live signatures a month and a full test mode. No card required.

7 files · copy and run

## The working code: a signup clickwrap in Django

Seven files in an app named `signup`: a client module, the views, two templates, the model, the webhook and the URLs. `pip install requests` is the only dependency besides Django.

**API client**

`signup/esign.py`

```python
# signup/esign.py
# The whole client. There is no Python package to install: these are plain HTTPS calls with the secret key.
import os
import time
from urllib.parse import quote

import requests

API = os.environ.get("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1")
SEALED = {"recorded", "timestamped", "anchored"}


def call(method, path, json=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {os.environ['ESIGNCOMPLY_API_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for _ in range(3):
        response = requests.request(method, API + path, headers=headers, json=json, timeout=10)
        if response.status_code != 429:
            break
        time.sleep(1)  # rate limited: the window is one second (the Free plan allows 2 requests per second)
    response.raise_for_status()
    return response.json()


# POST /v1/sessions. The response carries client_token, api_url and the pinned documents.
def create_session(signer, url):
    return call("POST", "/sessions", idempotency_key=f"signup-{signer['external_id']}", json={
        "profile": os.environ["ESIGNCOMPLY_PROFILE_ID"],
        "signer": signer,
        "documents": [
            {"document": os.environ["ESIGNCOMPLY_TERMS_ID"], "version": "current"},
            {"document": os.environ["ESIGNCOMPLY_PRIVACY_ID"], "version": "current"},
        ],
        "context": {"url": url, "locale": "en-US", "purpose": "account_signup"},
    })


# GET /v1/records/{id}
def get_record(record_id):
    return call("GET", f"/records/{quote(record_id, safe='')}")


# GET /v1/documents/{id}/versions/{version_id}/content
def get_document_content(document_id, version_id):
    return call("GET", f"/documents/{document_id}/versions/{quote(version_id, safe='')}/content")


# Server confirmation: read the record with the secret key and compare it with
# what this server saved when it created the session.
def confirm_record(record_id, acceptance, livemode):
    try:
        record = get_record(record_id)
    except requests.RequestException:
        return None  # a made-up ID, a record from the other environment, or the API could not be reached
    confirmed = (
        record["status"] in SEALED
        and record["livemode"] is livemode
        and record["signer"]["external_id"] == acceptance.signer_id
        and sorted(d["version_id"] for d in record["documents"]) == sorted(acceptance.document_version_ids)
    )
    return record if confirmed else None
```

**Views**

`signup/views.py`

```python
# signup/views.py
import json
import os
import uuid

import requests
from django.conf import settings
from django.contrib.auth import get_user_model, login
from django.http import Http404, JsonResponse
from django.shortcuts import render
from django.utils.dateparse import parse_datetime
from django.views.decorators.http import require_GET, require_POST

from . import esign
from .models import Acceptance

LEGAL = {"terms": "ESIGNCOMPLY_TERMS_ID", "privacy": "ESIGNCOMPLY_PRIVACY_ID"}


# POST /signup/ceremony/ creates the session and returns only the client token.
@require_POST
def ceremony(request):
    data = json.loads(request.body)
    country = data["country"].upper()
    # Your identifier for this person. Keep using it for them in later sessions.
    signer = {"external_id": str(uuid.uuid4()), "email": data["email"], "class": "consumer", "country": country}
    if country == "US" and data.get("state"):
        signer["region"] = f"US-{data['state'].upper()}"

    try:
        session = esign.create_session(signer, request.build_absolute_uri("/signup/"))
    except requests.RequestException:
        return JsonResponse({"error": "ceremony_unavailable"}, status=502)

    # Server-owned state: the signer and the versions this session pinned.
    Acceptance.objects.create(
        signer_id=signer["external_id"],
        session_id=session["id"],
        document_version_ids=[d["version_id"] for d in session["documents"]],
    )
    request.session["esign_session_id"] = session["id"]

    # Only these go to the browser. Never the key, never the whole session.
    return JsonResponse({
        "clientToken": session["client_token"],
        "apiUrl": session["api_url"],
        "documents": session["documents"],
    })


# GET /signup/ renders the form. POST /signup/ confirms the record, then creates the account.
def signup(request):
    if request.method != "POST":
        return render(request, "signup/signup.html")

    acceptance = Acceptance.objects.filter(session_id=request.session.get("esign_session_id"), user=None).first()
    record_id = request.POST.get("record_id")  # from the browser: a claim to check
    record = None
    if acceptance and record_id:
        record = esign.confirm_record(record_id, acceptance, settings.ESIGNCOMPLY_LIVE)
    if record is None:
        # Not confirmed: no account. The browser shows the "could not confirm" message.
        return JsonResponse({"error": "not_confirmed"}, status=409)

    email = request.POST["email"]
    user = get_user_model().objects.create_user(username=email, email=email, password=request.POST["password"])
    acceptance.user = user
    acceptance.record_id = record["id"]
    acceptance.receipt = record["receipt"]
    acceptance.accepted_at = parse_datetime(record["signed_at"])
    acceptance.save()
    login(request, user)
    return JsonResponse({"ok": True})


# GET /legal/terms/?v=dv_... serves one registered version, unmodified.
@require_GET
def legal(request, slug):
    if slug not in LEGAL:
        raise Http404
    try:
        content = esign.get_document_content(os.environ[LEGAL[slug]], request.GET.get("v", "current"))
    except requests.RequestException:
        raise Http404
    return render(request, "signup/legal.html", {"content": content})
```

**Signup form**

`signup/templates/signup/signup.html`

```html
{# signup/templates/signup/signup.html #}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Create your account</title>
    <style>
      body { font: 16px/1.5 system-ui, sans-serif; color: #111; max-width: 420px; margin: 40px auto; padding: 0 20px; }
      label { display: block; margin-bottom: 12px; }
      #assent label { display: inline; }
      #assent a { color: #2563eb; text-decoration: underline; }
    </style>
  </head>
  <body>
    <form id="signup" action="{% url 'signup' %}" method="post">
      {% csrf_token %}
      <label>Email <input name="email" type="email" autocomplete="email" required data-signer></label>
      <label>Country <input name="country" value="US" maxlength="2" required data-signer></label>
      <label>State <input name="state" placeholder="CA" maxlength="2" data-signer></label>
      <label>Password <input name="password" type="password" autocomplete="new-password" minlength="12" required></label>

      <div id="assent">
        <input id="agree" type="checkbox" disabled>
        <label for="agree">
          By checking the box and clicking Create account, you agree to the
          <a id="tos-link" href="{% url 'legal' 'terms' %}" target="_blank" rel="noopener">Terms of Service</a>
          and acknowledge the
          <a id="privacy-link" href="{% url 'legal' 'privacy' %}" target="_blank" rel="noopener">Privacy Notice</a>.
        </label>
        <p><button id="create-account" type="submit" disabled>Create account</button></p>
        <p>Acme uses Esign Comply to record this event on its behalf. See Acme's Privacy Notice for purposes and roles.</p>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const form = document.querySelector("#signup");
      const fields = form.elements;
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");
      const tosLink = document.querySelector("#tos-link");
      const privacyLink = document.querySelector("#privacy-link");
      const INCONCLUSIVE = "We could not confirm whether your acceptance was recorded. Please wait while we check.";
      let ceremony = null;
      let startedFor = null; // the signer details the current session was created with
      let run = 0;
      let timer;
      const details = () => JSON.stringify([fields.email.value, fields.country.value, fields.state.value]);

      // A session belongs to the signer details it was created with. Without one, the box stays disabled.
      function drop() {
        run += 1; // a start that is still in flight is ignored
        if (ceremony) ceremony.destroy();
        ceremony = null;
        startedFor = null;
        agree.checked = false; // a new session must find the box unchecked
        agree.disabled = submit.disabled = true;
        message.textContent = "";
      }

      async function start() {
        clearTimeout(timer);
        if (startedFor === details()) return; // a session for these details exists or is on its way
        drop();
        if (!fields.email.value || !fields.email.checkValidity()) return;
        startedFor = details();
        const current = run;

        try {
          // Your server creates the session with the secret key and returns only the client token.
          const response = await fetch("{% url 'signup_ceremony' %}", {
            method: "POST",
            headers: { "Content-Type": "application/json", "X-CSRFToken": fields.csrfmiddlewaretoken.value },
            body: JSON.stringify({ email: fields.email.value, country: fields.country.value, state: fields.state.value }),
          });
          if (!response.ok) throw new Error("We could not start the signup. Reload the page to try again.");
          const { clientToken, apiUrl, documents } = await response.json();
          if (current !== run) return; // a field changed while the request was in flight

          const attached = await EsignComply.attach({ clientToken, apiUrl });
          if (current !== run) return attached.destroy();
          ceremony = attached;
          ceremony.on("change", ({ remainingSteps }) => {
            submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
          });
          ceremony.on("expired", () => {
            drop();
            start();
          });

          // Point each link at the exact version this session pinned, then report it.
          const [terms, privacy] = documents;
          tosLink.search = "?v=" + terms.version_id;
          privacyLink.search = "?v=" + privacy.version_id;
          await ceremony.presentDocument({ versionId: terms.version_id, mode: "hyperlink", link: tosLink });
          await ceremony.presentDocument({ versionId: privacy.version_id, mode: "hyperlink", link: privacyLink });

          // The region holds the notice, the links, the checkbox and the button.
          await ceremony.observeAssent({ region: document.querySelector("#assent"), checkbox: agree, submit });
          agree.disabled = false; // the box can be ticked only while the SDK is watching it
        } catch (error) {
          if (current === run) message.textContent = error.message;
        }
      }

      // When a signer field changes, drop the session at once. Start a new one when the
      // field is left, or when the typing stops.
      form.addEventListener("input", (event) => {
        if (!event.target.matches("[data-signer]")) return;
        drop();
        clearTimeout(timer);
        if (event.target !== fields.email) timer = setTimeout(start, 800); // an email is finished when its field is left
      });
      form.addEventListener("change", (event) => {
        if (event.target.matches("[data-signer]")) start();
      });
      start();

      form.addEventListener("submit", async (event) => {
        event.preventDefault();
        if (!ceremony) return;
        message.textContent = "";
        try {
          const result = await ceremony.complete(); // the signing act: { recordId, receipt, verifyUrl, status }
          const body = new FormData(form);
          body.set("record_id", result.recordId);
          // Your server confirms the record with the secret key before it creates the account.
          const finished = await fetch(form.action, { method: "POST", body, headers: { Accept: "application/json" } });
          if (!finished.ok) throw new Error("Not confirmed");
          location.assign("/");
        } catch (error) {
          // A refusal carries a message and a fix: keep the form. Anything else is inconclusive.
          const refused = error instanceof EsignComply.EsignComplyError && error.code !== "network_error" && error.status < 500;
          message.textContent = refused ? error.message : INCONCLUSIVE;
        }
      });
    </script>
  </body>
</html>
```

**Model**

`signup/models.py`

```python
# signup/models.py
from django.conf import settings
from django.db import models


class Acceptance(models.Model):
    # Written when the session is created.
    signer_id = models.CharField(max_length=64)  # signer.external_id sent to Esign Comply
    session_id = models.CharField(max_length=64, unique=True)  # ses_...
    document_version_ids = models.JSONField()  # ["dv_...", "dv_..."]: the versions the session pinned
    # Filled in once the record is confirmed.
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
    record_id = models.CharField(max_length=64, unique=True, null=True)  # rec_...
    receipt = models.TextField(null=True)  # signed receipt (JWS, ES256)
    accepted_at = models.DateTimeField(null=True)  # the record's signed_at
    created_at = models.DateTimeField(auto_now_add=True)
```

**Document page**

`signup/templates/signup/legal.html`

```html
{# signup/templates/signup/legal.html #}
<!doctype html>
<html lang="{{ content.language }}">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Legal</title>
  </head>
  <body>
    {# The registered HTML, unmodified, and nothing else inside the article: the SDK hashes its text. #}
    <article data-esc-document="{{ content.version_id }}">{{ content.html|safe }}</article>
  </body>
</html>
```

**Webhook**

`signup/webhooks.py`

```python
# signup/webhooks.py
import base64
import hashlib
import hmac
import json
import os
import time

from django.conf import settings
from django.http import HttpResponse
from django.utils.dateparse import parse_datetime
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from . import esign
from .models import Acceptance


# Standard Webhooks: HMAC-SHA256 over "<webhook-id>.<webhook-timestamp>.<raw body>".
def verified(request):
    webhook_id = request.headers.get("webhook-id", "")
    timestamp = request.headers.get("webhook-timestamp", "")
    signatures = request.headers.get("webhook-signature", "")
    if not webhook_id or not timestamp.isdigit() or not signatures:
        return False
    if abs(time.time() - int(timestamp)) > 300:  # more than 5 minutes from now
        return False
    # The key is the base64-decoded part of the secret after "whsec_".
    key = base64.b64decode(os.environ["ESIGNCOMPLY_WEBHOOK_SECRET"].removeprefix("whsec_"))
    signed = f"{webhook_id}.{timestamp}.".encode() + request.body  # the raw bytes, never re-serialized JSON
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())
    # The header can hold several space-separated "v1,<signature>" values while a secret is rotated.
    return any(
        part.startswith("v1,") and hmac.compare_digest(part[3:].encode(), expected)
        for part in signatures.split(" ")
    )


# POST /webhooks/esigncomply/
@csrf_exempt
@require_POST
def esign_webhook(request):
    if not verified(request):
        return HttpResponse("Invalid signature", status=400)
    event = json.loads(request.body)

    # Deliveries are at-least-once. This only fills in a row that is still open, so a repeat changes nothing.
    if event["type"] == "record.completed":
        data = event["data"]
        acceptance = Acceptance.objects.filter(session_id=data["session_id"], record_id=None).first()
        if (
            acceptance
            and event["livemode"] is settings.ESIGNCOMPLY_LIVE
            and data["signer_external_id"] == acceptance.signer_id
            and sorted(d["version_id"] for d in data["documents"]) == sorted(acceptance.document_version_ids)
        ):
            record = esign.get_record(data["record_id"])  # the payload carries no receipt
            acceptance.record_id = record["id"]
            acceptance.receipt = record["receipt"]
            acceptance.accepted_at = parse_datetime(record["signed_at"])
            acceptance.save()

    return HttpResponse(status=200)  # also for event types this code does not know
```

**URLs**

`signup/urls.py`

```python
# signup/urls.py
# Include it from the project urls.py: path("", include("signup.urls"))
from django.urls import path

from . import views, webhooks

urlpatterns = [
    path("signup/", views.signup, name="signup"),
    path("signup/ceremony/", views.ceremony, name="signup_ceremony"),
    path("legal/<slug:slug>/", views.legal, name="legal"),
    path("webhooks/esigncomply/", webhooks.esign_webhook),
]
```

## What each file does

Seven files, four jobs: create the session in a view, collect the acceptance in your own template, confirm the record before `create_user`, and keep the receipt next to the user.

### `esign.py`: the whole client in one module

`signup/esign.py`

The server SDK is for Node, so Django talks to the REST API directly. `call` sends one request with `Authorization: Bearer <key>` and, on a `POST`, an `Idempotency-Key`. `create_session` is `POST /v1/sessions` with your profile, the signer and both documents at version `current`. `httpx` is a drop-in swap for `requests` here.

`confirm_record` guards the signup. It reads `GET /v1/records/{id}` with the secret key and returns the record only when the status is `recorded`, `timestamped` or `anchored`, `livemode` is what this deployment expects, and the signer and the exact set of document versions equal what the `Acceptance` row holds. A `429` is retried after one second: the Free plan allows 2 requests per second, and one signup makes three calls close together.

### `views.py`: start the ceremony, finish the signup, serve the documents

`signup/views.py`

`ceremony` answers the form's first request. It makes a signer ID, creates the session, saves one `Acceptance` row with the signer ID and the version IDs the session pinned, and keeps the session ID in the Django session. Three things go back to the browser: the client token, the API URL and the pinned documents. The key and the rest of the session stay on the server.

`signup` handles the final POST. The record ID in it came from the browser, so it is a claim. The view finds the open row for this Django session, calls `confirm_record` and creates the user only when the record matches. Then it writes the user, the record ID, the signed receipt and the accepted time onto the row. `legal` serves one registered version of a document by its ID.

### `signup.html`: your notice, your checkbox, your button

`signup/templates/signup/signup.html`

A complete page you can restyle. The notice names the button and both documents, the links are underlined and coloured apart from the text around them, and the checkbox starts unchecked and disabled. The script enables it only after `observeAssent` is watching, so every tick is one the SDK saw happen.

The script loads the browser SDK from `https://esigncomply.com/sdk/v1/esigncomply.js`, posts the email, country and state to `ceremony` with the CSRF token in the `X-CSRFToken` header, and calls `EsignComply.attach` with the client token. `presentDocument` reports each link, the `change` event opens the button when the signing act is the only step left, and `complete()` runs from the real click. The record ID then goes to `signup` with the rest of the form. Edit the email, country or state and the session is dropped and started again, because a session belongs to the signer details it was created with.

### `models.py`: the `Acceptance` model

`signup/models.py`

One row per ceremony. `signer_id`, `session_id` and `document_version_ids` are written when the session is created and are the server-owned state the confirmation compares against. `user`, `record_id`, `receipt` and `accepted_at` are filled in once the record is confirmed. `python manage.py makemigrations signup` writes the migration.

The receipt is a compact signed token (ES256) that names the record hash. Store it as text. A row with no record ID is a signup that was started and abandoned: sessions expire after 30 minutes, so open rows older than a day are safe to delete.

### `legal.html`: the registered version, unmodified

`signup/templates/signup/legal.html`

The `legal` view fetches one version by the ID in `?v=` and this template prints the returned HTML inside `<article data-esc-document>`, with `|safe` and nothing else in the article. When the form reports a link, the browser SDK reads this page, hashes the article's text and sends the hash, and the API compares it with the registered version (rule `CR-08`). Legal text never goes into a template or a fixture.

### `webhooks.py`: verify the signature, fill the open row

`signup/webhooks.py`

`record.completed` arrives once a record is sealed, including when the browser closed before `signup` ran. `verified` works on `request.body`, the raw bytes: it rejects a timestamp more than 5 minutes from now and recomputes HMAC-SHA256 over `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed with the base64-decoded part of the secret after `whsec_`. `hmac.compare_digest` keeps the comparison constant-time.

The view is `csrf_exempt` because the signature is the authentication. Deliveries are at-least-once, and the handler only fills a row that is still open, so a repeat changes nothing.

### `urls.py`: four paths

`signup/urls.py`

The signup page, the session endpoint, the document pages and the webhook. The absolute URL of `/signup/` is what the session declares as `context.url`. In live mode it has to be inside your registered domain.

Test mode

## Run it

From an empty account to a sealed test record on `localhost:8000`. No domain, no card and no package beyond `requests`.

1. **Create a free account and a test key**

   Sign up, then choose Create test key in the dashboard. The key starts with `esc_test_` and is shown once. The Free plan needs no card, and test keys work on `localhost` on any port with no domain.

2. **Register your two documents and a signup profile**

   In the dashboard, add a document named Terms of Service and one named Privacy Notice, publish a version of each, and create a profile with method `checkbox` and level `L1`. The names matter: the notice in the form names each document by its title, and rule `CR-02` looks for both. Copy the three IDs.

3. **Set the environment variables and one setting**

   Export the variables in the shell that runs Django. Then add `ESIGNCOMPLY_LIVE = False` to `settings.py`, and set it to `True` in production only: the confirmation uses it to refuse a test record in production.

   Terminal

   ```bash
   export ESIGNCOMPLY_API_KEY=esc_test_us_...       # the test key, shown once in the dashboard
   export ESIGNCOMPLY_PROFILE_ID=prof_signup_4f1a   # the signup profile: checkbox, L1
   export ESIGNCOMPLY_TERMS_ID=doc_8Hq2             # Terms of Service
   export ESIGNCOMPLY_PRIVACY_ID=doc_Pv71           # Privacy Notice
   export ESIGNCOMPLY_WEBHOOK_SECRET=whsec_...      # only for the webhook
   # An EU key (esc_test_eu_...) also needs:
   # export ESIGNCOMPLY_API_URL=https://api.eu.esigncomply.com/v1
   ```

4. **Migrate and start the server**

   Add `signup` to `INSTALLED_APPS` and include `signup.urls` from your project URLs first.

   `python manage.py makemigrations signup && python manage.py migrate && python manage.py runserver`

5. **Sign up once**

   Open `http://localhost:8000/signup/`. Enter an email and move to the next field: the checkbox unlocks when the session is attached. Tick it and click Create account.

6. **Open the test record**

   The dashboard lists one new test record under Records. It shows what Esign Comply observed from the browser (the page attached, both documents presented, the notice captured, the tick, the signing act), the conformance findings and the evidence report, watermarked TEST. Your `acceptances` row holds the same record ID and its signed receipt.

7. **Run the conformance check**

   The checker is a Node CLI, so it needs Node.js 20.19 or later on your machine, not in your project. The command reads `ESIGNCOMPLY_API_KEY` from your shell and takes test keys only. It opens your page in headless Chromium at 390 by 844, 768 by 1024 and 1440 by 900, tries to submit without the tick and with a scripted click, then signs up for real at each size, so expect three test users in your development database. Every finding names its rule, the measurement and the fix, and the exit code fails a CI build. This page, as written, ends with `0 block, 0 warn`.

   `npx esigncomply@latest check --url http://localhost:8000/signup/`

[Create a free account](https://esigncomply.com/signup) · [What test mode does](https://esigncomply.com/docs/guides/test-mode) · [The conformance rules](https://esigncomply.com/docs/conformance)

Live mode

## Going live

Nothing in the app changes between test and live except four values and one setting.

[See pricing](https://esigncomply.com/pricing) · [Register a domain](https://esigncomply.com/docs/guides/domains)

1. **Register your domain**

   Enter your production host in the dashboard under Domains. Registering `app.example.com` covers `example.com` and every subdomain, and every plan, Free included, covers that one domain.

2. **Verify it with one TXT record**

   Add a TXT record named `_esigncomply` with the value `esc-verify=<token>` that the dashboard shows. Esign Comply checks every minute for the first hour. Leave the record in place: it is checked again every day.

3. **Add your organization details**

   Enter your organization's legal name and country in the dashboard. The Free plan covers 10 live signature events a month with no checkout. Starter is $200 per year for 2,000 live signature events, and Unlimited is $1,200 per year. One event is one signer's completed signing act, so the terms and the privacy notice accepted together at signup count once.

4. **Switch to the live key**

   Create a live key (`esc_live_...`) and set it in your production environment only. Copy your documents and profile to live from the dashboard, set the live IDs beside the key, and set `ESIGNCOMPLY_LIVE = True` in production settings. From then on the confirmation refuses any test record there.

In live mode `context.url` has to be inside your registered domain, browser calls are accepted only from it, and a finding at Block level stops the record from being sealed. Run the conformance check until nothing blocks before you switch keys.

Copy-paste prompt

## Have your AI tool do it instead

Paste this into Cursor, Claude Code or any coding agent that is open on your Django project. It names the two things a tool gets wrong on this stack: there is no Python package, and the browser SDK comes from a script tag.

The [prompt generator](https://esigncomply.com/product/prompt-generator) writes the long version: your own document and profile IDs, the rule packs for your regions and the stack you pick, in one prompt.

[Generate a prompt](https://esigncomply.com/product/prompt-generator)

Prompt: clickwrap in Django

```
Add a signup clickwrap to this Django project with Esign Comply. A new user accepts our Terms of Service and Privacy Notice before the account is created. We render every screen. Esign Comply observes it and keeps the independent record.

Read these first and follow them exactly:
- https://esigncomply.com/setup.md
- https://esigncomply.com/auth.md
- https://esigncomply.com/llms.txt
- https://esigncomply.com/guides/django-clickwrap (working code for this stack: use it as the reference)

Stack
- There is no Esign Comply package on PyPI. Call the REST API with requests: Authorization: Bearer with os.environ["ESIGNCOMPLY_API_KEY"], and an Idempotency-Key on POST requests.
- Load the browser SDK with <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>. It defines the global EsignComply.

Build
1. A POST view creates the session with POST /v1/sessions and returns only client_token, api_url and the pinned documents. Save the signer ID and the version IDs on an Acceptance model.
2. The signup template: attach the SDK to our own unchecked checkbox and our Create account button. Present each document link, observe the assent container, and call complete() from the user's real click. Send the CSRF token in X-CSRFToken.
3. The signup view: before create_user, read GET /v1/records/{id} and require status recorded, timestamped or anchored, the expected livemode, and the saved signer ID and version IDs. Store the record ID and the receipt on the Acceptance row.

Never
- Never invent API methods, packages or legal wording.
- Never pre-check the box, auto-submit or click for the user.
- Never put the secret key in client code, in a template or in the repository, and never print it.
- Never create the account before the server has confirmed the record.

If anything conflicts with existing code, stop and ask me. Finish with npx esigncomply@latest check --url http://localhost:8000/signup/ and fix every finding marked "block".
```

### Open the page for your AI tool

- [Cursor](https://esigncomply.com/build/cursor)
- [Claude Code](https://esigncomply.com/build/claude-code)
- [Codex](https://esigncomply.com/build/codex)
- [Windsurf](https://esigncomply.com/build/windsurf)
- [GitHub Copilot](https://esigncomply.com/build/github-copilot)
- [Devin](https://esigncomply.com/build/devin)
- [Lovable](https://esigncomply.com/build/lovable)
- [v0](https://esigncomply.com/build/v0)
- [Bolt](https://esigncomply.com/build/bolt)
- [Replit](https://esigncomply.com/build/replit)
- [ChatGPT](https://esigncomply.com/build/chatgpt)
- [Grok](https://esigncomply.com/build/grok)
- [Grokbot](https://esigncomply.com/build/grokbot)
- [Muse](https://esigncomply.com/build/muse)
- [All AI tools](https://esigncomply.com/build#tools)

## Questions about a clickwrap in Django

### Is there an Esign Comply package for Django or Python?

No, and the integration does not need one. The server SDK exists for Node. A Django project calls the REST API with requests or httpx, and a signup clickwrap uses three calls: POST /v1/sessions, GET /v1/records/{id} and one GET for the registered document text. The esign.py module on this page is the whole client.

### How do I add a clickwrap agreement to a Django signup form?

Create a session in a view with your secret key and return only the client token. In the template, load the browser SDK with a script tag and attach it to your own unchecked checkbox and submit button. When the signer clicks, the SDK returns a record ID. Confirm that record in your signup view with GET /v1/records/{id} before create_user, and store the record ID and receipt on an Acceptance model.

### How does the clickwrap work with Django's CSRF protection?

The two browser requests carry the token Django already issues. The session request sends it in the X-CSRFToken header, and the final signup request posts the form, which includes csrfmiddlewaretoken. Only the webhook view is csrf_exempt, because Esign Comply signs each delivery and the view verifies that signature instead.

### How do I know which version of the terms a user accepted?

Read document_version_ids on the user's Acceptance row. Each ID is one immutable version, and the sealed record pins the same versions by SHA-256 hash. When you publish a new version as a material change, GET /v1/signers/{external_id}/status lists what that signer still has to accept, using the signer ID stored on the same row.

[Read the re-acceptance guide](https://esigncomply.com/docs/guides/reacceptance)

### Can I run the conformance check on a Django project?

Yes. The check is a command-line tool that opens any URL, so it does not care what serves the page. Run npx esigncomply@latest check --url http://localhost:8000/signup/ with your test key in the shell. It signs up at three window sizes and prints each finding with its rule ID, the measurement and the fix.

[Read the conformance rules](https://esigncomply.com/docs/conformance)

### The same clickwrap in another stack

- [Next.js and Supabase](https://esigncomply.com/guides/nextjs-supabase-clickwrap)
- [Rails](https://esigncomply.com/guides/rails-clickwrap)
- [Laravel](https://esigncomply.com/guides/laravel-clickwrap)
- [React Native](https://esigncomply.com/guides/react-native-clickwrap)
- [All stack guides](https://esigncomply.com/guides)

[Build your own clickwrap](https://esigncomply.com/build/clickwrap) · [Use cases with live demos](https://esigncomply.com/use-cases) · [Clickwrap and browsewrap compared](https://esigncomply.com/learn/clickwrap-vs-browsewrap)

## Add the signup app to your Django project. Leave the record to us.

[Get started](https://esigncomply.com/signup) · [Documentation](https://esigncomply.com/docs)

Free plan: 10 live signatures a month and a full test mode. No card required.

---

Every page on esigncomply.com has a Markdown version at the same URL plus `.md` (the home page is `https://esigncomply.com/index.md`). https://esigncomply.com/llms.txt lists them.
