Django
Integrate Swetrix with your Django application to track page views, monitor errors, and capture custom events — all while staying privacy-friendly and GDPR-compliant.
This guide covers traditional Django projects using the Django template engine, as well as tips for Django REST Framework setups with a JavaScript frontend.
Installation
The recommended approach is to add the Swetrix tracking script to your base template so it loads on every page.
1. Add the tracking script to your base template
Django projects typically have a base template that all other templates extend via {% extends 'base.html' %}. Open (or create) your templates/base.html and add the Swetrix script inside the <head> tag, and the initialisation snippet before the closing </body> tag:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}My Site{% endblock %}</title>
{% block styles %}{% endblock %}
<!-- Swetrix Analytics -->
<script src="https://swetrix.org/swetrix.js" defer></script>
</head>
<body>
{% block content %}{% endblock %}
<!-- Swetrix Analytics -->
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('YOUR_PROJECT_ID')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
{% block scripts %}{% endblock %}
</body>
</html>
Replace YOUR_PROJECT_ID with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.
2. Disable tracking in development (recommended)
To avoid polluting your analytics with local page views, use Django's settings.DEBUG flag to only include the script in production. First, make sure DEBUG is available in your templates by adding django.template.context_processors.debug to your context processors (it's included by default).
Then wrap the snippets:
{% if not debug %}
<script src="https://swetrix.org/swetrix.js" defer></script>
{% endif %}
And for the body initialisation:
{% if not debug %}
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('YOUR_PROJECT_ID')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
{% endif %}
During development, Swetrix ignores localhost traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set devMode: true:
swetrix.init('YOUR_PROJECT_ID', { devMode: true })
Remember to remove this before deploying.
Store your Project ID in settings (optional)
Rather than hardcoding the Project ID in your template, you can manage it through Django's settings and a custom context processor. This keeps configuration in one place and makes it easy to use different IDs per environment.
1. Add to your settings (e.g. settings.py):
import os
SWETRIX_PROJECT_ID = os.environ.get('SWETRIX_PROJECT_ID', '')
2. Create a context processor (e.g. context_processors.py in your main app):
from django.conf import settings
def swetrix(request):
return {
'SWETRIX_PROJECT_ID': getattr(settings, 'SWETRIX_PROJECT_ID', ''),
}
3. Register it in your settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
# ...existing processors
'myapp.context_processors.swetrix',
],
},
},
]
4. Reference it in your template:
{% if SWETRIX_PROJECT_ID %}
<script src="https://swetrix.org/swetrix.js" defer></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('{{ SWETRIX_PROJECT_ID }}')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid={{ SWETRIX_PROJECT_ID }}"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
{% endif %}
Set the environment variable in production:
export SWETRIX_PROJECT_ID=YOUR_PROJECT_ID
Check your installation
Deploy your application (or temporarily enable devMode) and visit a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.
Error tracking
Enable automatic client-side error monitoring by adding trackErrors() to the initialisation snippet. This captures unhandled JavaScript errors and reports them to Swetrix.
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('YOUR_PROJECT_ID')
swetrix.trackViews()
swetrix.trackErrors()
})
</script>
Errors will appear in the Errors tab of your project dashboard. See the tracking script reference for options like sampleRate and callback.
Tracking custom events
Custom events let you track specific user interactions — form submissions, button clicks, feature usage, and more. Since the Swetrix script is loaded globally, you can call swetrix.track() from any inline script or JavaScript file.
Example: tracking form submissions
Track when users submit a contact form:
<form id="contact-form" method="POST" action="{% url 'contact' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send message</button>
</form>
<script>
document.getElementById('contact-form')?.addEventListener('submit', function () {
if (typeof swetrix !== 'undefined') {
swetrix.track({
ev: 'CONTACT_FORM_SUBMITTED',
meta: {
page: window.location.pathname,
},
})
}
})
</script>
Example: tracking outbound links
Track clicks on external links across your site. Add this to your base template:
<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('a[href^="http"]').forEach(function (link) {
if (link.hostname !== window.location.hostname) {
link.addEventListener('click', function () {
if (typeof swetrix !== 'undefined') {
swetrix.track({
ev: 'OUTBOUND_CLICK',
meta: { url: link.href },
})
}
})
}
})
})
</script>
Event naming rules
Event names must:
- Contain any characters (including spaces, unicode, etc.)
- Be no longer than 256 characters
We recommend UPPER_SNAKE_CASE for consistency (e.g. CONTACT_FORM_SUBMITTED, OUTBOUND_CLICK).
Using Swetrix with HTMX
If your Django application uses HTMX for dynamic page updates, the Swetrix script loaded in your base template will still track the initial page load. For HTMX-driven navigations that change the URL (using hx-push-url), Swetrix's trackViews() automatically detects History API changes and tracks them.
If you use HTMX to swap content without changing the URL and want to track those interactions, use custom events:
<button hx-post="/api/subscribe" hx-swap="outerHTML"
onclick="if(typeof swetrix!=='undefined') swetrix.track({ ev: 'SUBSCRIBE_CLICKED' })">
Subscribe
</button>
Using Swetrix with Django and a JavaScript frontend
If you use Django as an API backend (e.g. with Django REST Framework) paired with a JavaScript frontend, add the Swetrix tracking to your frontend project instead:
npm install swetrix
import * as Swetrix from 'swetrix'
Swetrix.init('YOUR_PROJECT_ID')
Swetrix.trackViews()
See the relevant frontend framework integration guide (React, Vue, etc.) for framework-specific details.
Further reading
- Tracking script reference — full API documentation for
init(),track(),trackViews(),trackErrors(), and more. - Swetrix npm package — package details and changelog.
- Django documentation — official Django docs.
Help us improve Swetrix
Was this page helpful to you?
