Django's APPEND_SLASH Redirect Cannot Carry POST Data

In progress Django

APPEND_SLASH is a Django setting (in settings.py, True by default), applied by CommonMiddleware. When a URL doesn't match any pattern but the same URL with a trailing slash would, Django answers with a permanent redirect to the slashed URL. That's harmless for links, which the browser simply follows with a GET. For a form posted to the URL without the slash, a redirect would lose the submitted data, so in debug mode Django raises an error instead and in production the browser follows the redirect with a GET.

What Happens

Request Pattern contact/ exists Result
GET /contact yes 301 to /contact/, then the page
POST /contact with DEBUG = True yes RuntimeError: the redirect can't keep the POST data, change the form to point to /contact/
POST /contact with DEBUG = False yes 301 to /contact/; the browser re-requests it with GET, the form data is gone
GET /contact no slashed version either 404

Keep URLs Consistent

  • Define patterns with a trailing slash (path("contact/", ...)), the Django convention that APPEND_SLASH supports.
  • Generate links and form actions with {% url %} or reverse() instead of typing paths.
  • APIs called by other programs should be called with the exact path: clients and proxies don't always follow redirects on POST, and some turn it into a GET.

References

Review cards

Flashcard Why does `APPEND_SLASH` not carry POST data in Django?

Because a redirect from a non-matching URL to a matching URL with a trailing slash would lose the POST data, so in production the browser re-requests the URL with a GET which results in the loss of the form data.

Flashcard What happens if `DEBUG = True` and a form is submitted to a URL without a trailing slash that has a matching pattern with one?

Django raises a RuntimeError because the redirect can't keep the POST data, and the form should be pointed to the canonical URL.