Skip to content

Instantly share code, notes, and snippets.

@simkimsia
Forked from adamchainz/_base.html
Last active June 4, 2022 12:44
Show Gist options
  • Save simkimsia/d602116b35d143de98afc729f8d3276f to your computer and use it in GitHub Desktop.
Save simkimsia/d602116b35d143de98afc729f8d3276f to your computer and use it in GitHub Desktop.
Django HTMX CSRF setup for htmx 1.1.0 and django 3.1
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% block meta_tags %}
<meta name="csrf-token" content="{{ csrf_token }}">
{% endblock %}
</head>
<body>
{% block js %}
<script src="https://unpkg.com/[email protected]"></script>
<script>
const csrf_token = document.querySelector('meta[name="csrf-token"]').content;
htmx.on('htmx:configRequest', (evt) => {
if (csrfToken) {
evt.detail.headers['X-CSRFToken'] = csrf_token;
}
});
</script>
{% endblock %}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment