All articles

Django 8 min read AgiCAD studio

Stopping Form Spam With a Honeypot and a Time Trap

Two server-side tricks that stop cheap, automated contact-form spam without loading a third-party script, asking for consent, or taxing real users.

A garden mailbox form where a honey pot catches spam robot bees while a person calmly posts a letter

A marketing site goes live with a three-field contact form. Two weeks later the inbox has eleven enquiries, nine of which offer SEO services in broken English and link to a domain nobody should click. The form works perfectly. That is the problem.

The symptom

Bot submissions on a small site rarely look sophisticated. In the logs they have a shape: they arrive within a second of the page being fetched, they fill every field they can find including ones no human can see, they come from a handful of user agents, and they never request the CSS or the images. They are cheap, automated, and aimed at every form on the internet rather than at you specifically.

That last point is what makes them beatable. A script pointed at a million URLs cannot afford a per-site adjustment, so anything that requires one is enough to make it move on.

Why we do not reach for reCAPTCHA first

The reflex is to bolt on a CAPTCHA, and on a small marketing site that is the wrong first move. It loads a third-party script on every page carrying the form, which drags in a GDPR consent conversation because the script sets identifiers before anyone has agreed to anything; it costs real milliseconds in Core Web Vitals on the page you most want to be fast; and it taxes the honest visitor, because every extra second between deciding to get in touch and pressing send is a conversion you might not get.

Two server-side techniques cost nothing, ship no third-party code, and kill the cheap end of the spam spectrum. Neither defends against a determined human, and we come back to that at the end.

Technique one: the honeypot

A honeypot is a form field that a human never sees and a naive bot always fills. If it comes back with anything in it, the submission was not made by a person reading your page.

The details are where most implementations get it wrong.

Hide it off-canvas, not with display:none. Form-filling scripts have been skipping display:none and type="hidden" inputs for years, precisely because honeypots are old. An input positioned far outside the viewport is still a rendered, visible-to-the-DOM field, so a naive filler treats it like any other text input.

Keep humans out of it properly. Off-screen is not the same as inaccessible. Without tabindex="-1" a keyboard user tabs from the email field into a void and starts typing into your trap. Without aria-hidden="true" a screen reader announces it. Without autocomplete="off" the browser's own autofill cheerfully fills it in and locks a real person out of your form for reasons they cannot possibly diagnose. All three are mandatory, not polish.

Name it something a bot wants to fill. A field called honeypot is a giveaway. Field names like website or company_url are exactly what a link-spamming script is looking for. On this site the field is hp_field with the visible label "Website", alongside the real hidden field source and the timing field form_time.

<style>
/* belongs in your stylesheet; shown here for context */
.hp-field { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
</style>

<form method="post" action="/contact/">
  {% csrf_token %}

  <label for="id_name">Name</label>{{ form.name }}
  <label for="id_email">Email</label>{{ form.email }}
  <label for="id_message">Message</label>{{ form.message }}

  <div class="hp-field" aria-hidden="true">
    <label for="id_hp_field">Website</label>
    {{ form.hp_field }}
  </div>

  {{ form.source }}
  {{ form.form_time }}

  <button type="submit">Send</button>
</form>

An absolutely positioned input at left: -9999px is also the single most common false positive in a mobile horizontal-overflow audit. Six months from now, somebody (possibly you) will run a layout check, find an element sticking 9,999 pixels off the left edge, and "fix" it. Leave the comment in the stylesheet next to the rule, not only in the Django form, because the stylesheet is where that person will be looking.

Technique two: the time trap

The second signal is how long the form was on screen. A human reads the labels, thinks, and types; three seconds is an aggressively generous floor, and a script POSTs immediately. So stamp the render time into the form and compare it on submit. The naive version puts int(time.time()) into a hidden field, and the view subtracts it from time.time() on POST. A plain integer is fine for the cheap bots, because they replay whatever was in the field, and whatever was in the field is genuinely old by the time they submit. It is worthless against anything that reads the field name and substitutes its own number, which is a three-line change for the attacker.

Signing closes that. django.core.signing.TimestampSigner produces a value that carries its own timestamp and a signature over it, so a bot cannot forge a plausible age, and max_age gives you an expiry for free. If the form is worth defending at all, sign it. The cost is one import.

The complete implementation

The form does the detection, raising a dedicated exception rather than a ValidationError, because a validation error means "tell the user what to fix" and that is exactly what we do not want to do.

import time

from django import forms
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner

MIN_FILL_SECONDS = 3
MAX_FORM_AGE = 60 * 60

signer = TimestampSigner(salt="contact-form")


class BotDetected(Exception):
    """Raised when the submission is almost certainly automated."""


class ContactForm(forms.Form):
    name = forms.CharField(max_length=120)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)
    source = forms.CharField(required=False, widget=forms.HiddenInput)

    hp_field = forms.CharField(
        required=False,
        label="Website",
        widget=forms.TextInput(attrs={
            "class": "hp-field",
            "tabindex": "-1",
            "autocomplete": "off",
            "aria-hidden": "true",
        }),
    )
    form_time = forms.CharField(required=False, widget=forms.HiddenInput)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.is_bound:
            self.fields["form_time"].initial = signer.sign(str(int(time.time())))

    def clean_hp_field(self):
        value = self.cleaned_data.get("hp_field", "")
        if value.strip():
            raise BotDetected("honeypot filled: %r" % value[:80])
        return ""

    def clean_form_time(self):
        raw = self.cleaned_data.get("form_time", "")
        try:
            stamp = signer.unsign(raw, max_age=MAX_FORM_AGE)
            rendered_at = int(stamp)
        except (BadSignature, SignatureExpired, TypeError, ValueError):
            raise BotDetected("form_time missing, tampered or expired")
        if time.time() - rendered_at < MIN_FILL_SECONDS:
            raise BotDetected("submitted after %.1fs" % (time.time() - rendered_at))
        return raw

A non-ValidationError exception raised inside a clean_<field> method propagates straight out of form.is_valid(), which is what makes this pattern work: the view gets one clear place to decide what a caught bot sees.

import logging

from django.shortcuts import redirect, render

logger = logging.getLogger("contact.spam")


def contact(request):
    if request.method != "POST":
        return render(request, "website/contact.html", {"form": ContactForm()})

    form = ContactForm(request.POST)
    try:
        valid = form.is_valid()
    except BotDetected as exc:
        logger.info(
            "dropped bot submission: %s | ip=%s | ua=%.120s",
            exc,
            request.META.get("REMOTE_ADDR", "?"),
            request.META.get("HTTP_USER_AGENT", ""),
        )
        return redirect("contact_thanks")

    if valid:
        send_enquiry(form.cleaned_data)
        return redirect("contact_thanks")

    return render(request, "website/contact.html", {"form": form})

Answer a caught bot with success

Notice that the bot branch and the happy branch return the same thing. This is deliberate and it is the part people skip.

If you return a 403, or re-render the form with "suspicious submission detected", you have handed the spammer's tooling a signal. Automated submitters retry on failure with a different shape: fewer fields, a slower POST, a different user agent. A 200 and a thank-you page tells them the job is done, and they never come back to work out why nothing arrived. Silence is the whole strategy.

Proving the rules before you ship them

Timing logic is easy to get subtly wrong and awkward to test by hand, so we pull the decision into a pure function and run a table through it.

from django.conf import settings

settings.configure(SECRET_KEY="harness-only-not-a-real-key")

from django.core.signing import BadSignature, SignatureExpired, TimestampSigner

MIN_SECONDS = 3


def classify(hp_field, form_time, now):
    """Return 'accept', 'drop' (silent, looks like success) or 'reject'."""
    if hp_field.strip():
        return "drop"
    try:
        rendered_at = int(form_time)
    except (TypeError, ValueError):
        return "reject"
    elapsed = now - rendered_at
    if elapsed < MIN_SECONDS or elapsed > 3600:
        return "reject"
    return "accept"


NOW = 1_760_000_000
CASES = [
    ("empty honeypot, 10 s elapsed", "", str(NOW - 10), "accept"),
    ("filled honeypot, 10 s elapsed", "http://spam.example", str(NOW - 10), "drop"),
    ("honeypot holds whitespace only", "   ", str(NOW - 10), "accept"),
    ("1 s elapsed", "", str(NOW - 1), "reject"),
    ("exactly 3 s elapsed", "", str(NOW - 3), "accept"),
    ("missing form_time", "", "", "reject"),
    ("garbage form_time", "", "not-a-number", "reject"),
    ("form_time from the future", "", str(NOW + 60), "reject"),
    ("stale form, 2 h elapsed", "", str(NOW - 7200), "reject"),
]

for label, hp, ft, expected in CASES:
    got = classify(hp, ft, NOW)
    print("%s %-32s -> %-6s (expected %s)" % ("ok " if got == expected else "FAIL",
                                              label, got, expected))

signer = TimestampSigner(salt="contact-form")
token = signer.sign("contact")

try:
    signer.unsign(token, max_age=3600)
    print("ok   fresh token unsigns with max_age=3600")
except BadSignature as exc:
    print("FAIL fresh token:", exc)

try:
    signer.unsign(token, max_age=0.001)
    print("FAIL expired token was accepted")
except SignatureExpired:
    print("ok   expired token raises SignatureExpired (max_age=0.001)")

try:
    signer.unsign(token[:-1] + "x")
    print("FAIL tampered token was accepted")
except BadSignature:
    print("ok   tampered token raises BadSignature")
$ venv/bin/python spam_gate_test.py
ok  empty honeypot, 10 s elapsed     -> accept (expected accept)
ok  filled honeypot, 10 s elapsed    -> drop   (expected drop)
ok  honeypot holds whitespace only   -> accept (expected accept)
ok  1 s elapsed                      -> reject (expected reject)
ok  exactly 3 s elapsed              -> accept (expected accept)
ok  missing form_time                -> reject (expected reject)
ok  garbage form_time                -> reject (expected reject)
ok  form_time from the future        -> reject (expected reject)
ok  stale form, 2 h elapsed          -> reject (expected reject)
ok   fresh token unsigns with max_age=3600
ok   expired token raises SignatureExpired (max_age=0.001)
ok   tampered token raises BadSignature

The whitespace case is the one worth staring at. " " is not an empty string, and without the .strip() a browser that helpfully trims or pads the field would get a real person silently ignored. The upper bound matters too: without it, a form left open in a tab overnight is indistinguishable from a replayed one.

Pitfalls

  • Full-page caching. If the contact page is cached by a CDN or by Django's cache middleware, every visitor gets the same rendered form_time, and a cache entry older than MAX_FORM_AGE rejects everyone. Exclude the page from the cache, or inject the stamp with a small uncached request.
  • Rejections into a void. Log every drop with enough context to audit it. A silent filter you cannot inspect is indistinguishable from a broken form, and you will only find out when a client asks why nobody replied.

The same two fields are in place on this site and on the landing pages we build. They stop the automated form-fillers, at the cost of about sixty lines and zero extra requests.

When not to do this

Neither technique survives a targeted attacker. A headless browser drives a real DOM, so it sees the off-canvas field is off-canvas and skips it, and waiting ten seconds costs it nothing. A human paid to fill in forms defeats both trivially. For a high-value signup flow, an account-creation endpoint, or anything already under deliberate abuse, you need rate limiting, reputation scoring, email verification and probably a challenge. A honeypot is a filter for indiscriminate traffic, not a lock.

The second case is subtler: anywhere a false positive silently loses a real lead. A slow, silent drop is the worst failure mode in this design, because nobody on either side learns anything. If the form is the only way a customer can reach you, log the rejections to somewhere a person actually reads, and review them for the first month. If you cannot commit to that review, raise a visible error instead and accept the extra spam.

If your contact form is quietly filling with rubbish, or the form on your site needs the Django side built properly rather than bolted on, tell us what you are running. Start a project and we reply within two business days.

We ship and run our own products. We build yours the same way.

Start a project

Join the article list

We are collecting addresses now and will email new articles once the newsletter starts. No spam, unsubscribe any time.

Hour Blocks from $180reply within two business days Start a project