Disclaimer:
This post was created with the assistance of Gemini and/or ChatGPT for informational purposes. While given a quick look over, readers are encouraged to verify key facts independently.
To comply with GDPR and privacy laws, you must get user consent before loading tracking tools like Google Analytics. This post shows how to create a cookie-based consent banner using HTMX and Django. The banner will appear until the user accepts, and only then will Google Analytics be loaded based on a cookie value.
Steps to Add Cookie Consent with HTMX in Django
-
Create a Django View to Set Consent Cookie
In yourviews.py:from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def accept_cookie_consent(request): response = HttpResponse("ok") response.set_cookie("cookie_consent", "true", max_age=60*60*24*365) # 1 year return response -
Add URL Route for Consent
Inurls.py:from django.urls import path from . import views urlpatterns = [ path("cookie-consent/", views.accept_cookie_consent, name="cookie_consent"), ] -
Modify Your
base.htmlTemplate
Include HTMX and conditionally load Google Analytics only if the cookie is set:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Blog</title> <script src="https://unpkg.com/htmx.org@1.9.2"></script> {% if request.COOKIES.cookie_consent == "true" %} <script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '{{ GOOGLE_ANALYTICS_ID }}'); </script> {% endif %} </head> <body> <!-- Page content here --> {% if request.COOKIES.cookie_consent != "true" %} <div id="cookie-banner" style="position: fixed; bottom: 0; width: 100%; background: #333; color: #fff; padding: 1rem; text-align: center; z-index: 9999;"> This site uses cookies for analytics. <button hx-post="{% url 'cookie_consent' %}" hx-target="#cookie-banner" hx-swap="outerHTML" onclick="setTimeout(function(){ location.reload(); }, 500)" class="btn btn-sm btn-primary" >Accept</button> </div> {% endif %} </body> </html> -
Add Context Processor (Optional)
If you're storing your Analytics ID in Django settings:
Add to# context_processors.py def analytics_id(request): from django.conf import settings return {'GOOGLE_ANALYTICS_ID': settings.GOOGLE_ANALYTICS_ID}TEMPLATESsettings:'OPTIONS': { 'context_processors': [ ... 'yourapp.context_processors.analytics_id', ], }, -
Test the Banner
Visit your Django site. The banner appears on first visit. When you click "Accept", the cookie is set and the page reloads with Google Analytics enabled.
Note: This approach uses a secure cookie instead of localStorage, which is compatible with Django’s server-side rendering. You can further customize this to support cookie categories or non-reloading dynamic injection using JavaScript or HTMX.
Comments