Skip to content
Stack guide · Django

Clickwrap agreement in 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.

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.

signup/esign.py
# 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

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.

01

esign.py: the whole client in one module

signup/esign.pyView the file

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.

02

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

signup/views.pyView the file

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.

03

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

signup/templates/signup/signup.htmlView the file

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.

04

models.py: the Acceptance model

signup/models.pyView the file

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.

05

legal.html: the registered version, unmodified

signup/templates/signup/legal.htmlView the file

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.

06

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

signup/webhooks.pyView the file

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.

07

urls.py: four paths

signup/urls.pyView the file

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. 01

    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. 02

    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. 03

    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
    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. 04

    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. 05

    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. 06

    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. 07

    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/
Live mode

Going live

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

  1. 01
    Register your domainEnter 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. 02
    Verify it with one TXT recordAdd 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. 03
    Add your organization detailsEnter 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. 04
    Switch to the live keyCreate 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 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
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".

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

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

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

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

Working with an AI tool? This page is also available as Markdown: /guides/django-clickwrap.md