CodingBowl

How to Show a Cookie-Based Consent Banner Before Loading Google Analytics in Django Using HTMX

Published on 18 Jun 2025Web Analytics
image
Photo by Mollie Sivaram on Unsplash

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

  1. Create a Django View to Set Consent Cookie
    In your views.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
        
  2. Add URL Route for Consent
    In urls.py:
    
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path("cookie-consent/", views.accept_cookie_consent, name="cookie_consent"),
    ]
        
  3. Modify Your base.html Template
    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>
        
  4. Add Context Processor (Optional)
    If you're storing your Analytics ID in Django settings:
    
    # context_processors.py
    def analytics_id(request):
        from django.conf import settings
        return {'GOOGLE_ANALYTICS_ID': settings.GOOGLE_ANALYTICS_ID}
        
    Add to TEMPLATES settings:
    
    'OPTIONS': {
        'context_processors': [
            ...
            'yourapp.context_processors.analytics_id',
        ],
    },
        
  5. 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.

Meow! AI Assistance Note

This post was created with the assistance of Gemini AI and ChatGPT.
It is shared for informational purposes only and is not intended to mislead, cause harm, or misrepresent facts. While efforts have been made to ensure accuracy, readers are encouraged to verify information independently. Portions of the content may not be entirely original.

image
Photo by Yibo Wei on Unsplash