# Django

## Add Humblytics Analytics to a Django Site

### 1 · Sign up (or log in)

Visit humblytics.com → Start Free Trial. Finish signup—or log in to your existing workspace.

### 2 · Add your website in Humblytics

In the sidebar, click **Add Website**.

* **Domain** – enter `your-domain.com` (omit `https://` and `www`)
* **Site Name** – internal label (e.g. `Marketing-Django`)

Copy the snippet from **Install Tracking Code**:

html

```html
<!-- Start Humblytics Tracking Code -->
<script async src="https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE"></script>
<!-- End Humblytics Tracking Code -->
```

Keep this tab open—we'll return and click **Verify Website** once the tag is live.

### 3 · Add the script to your Django project

#### Option 1: Direct template integration (simple)

**Best for:** Quick setup, single environment

1. Open your base template file, typically:
   * `templates/base.html`
   * `templates/layout.html`
   * Or your project's main template that other templates extend
2. Add the Humblytics script just before `</head>`:

django

```django
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Site{% endblock %}</title>
    
    {% block extra_head %}{% endblock %}
    
    <!-- Humblytics Analytics -->
    {% if not debug %}
    <script async src="https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE"></script>
    {% endif %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
```

3. Ensure child templates extend this base:

django

```django
{% extends 'base.html' %}

{% block content %}
    <!-- Your page content -->
{% endblock %}
```

**Note**: `{% if not debug %}` prevents tracking in development when `DEBUG = True`.

#### Option 2: Using Django settings (recommended)

**Best for:** Production/staging environments, cleaner configuration

1. Add to your `settings.py`:

python

```python
# settings.py

# Humblytics Analytics
HUMBLYTICS_ID = os.environ.get('HUMBLYTICS_ID', '')

# Only track in production
ENABLE_ANALYTICS = not DEBUG and HUMBLYTICS_ID
```

2. Add to `.env` file (for production):

env

```env
HUMBLYTICS_ID=YOUR_ID_HERE
```

3. Create a context processor to make settings available in templates:

python

```python
# your_app/context_processors.py

from django.conf import settings

def analytics(request):
    return {
        'HUMBLYTICS_ID': settings.HUMBLYTICS_ID,
        'ENABLE_ANALYTICS': settings.ENABLE_ANALYTICS,
    }
```

4. Register the context processor in `settings.py`:

python

```python
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'your_app.context_processors.analytics',  # Add this line
            ],
        },
    },
]
```

5. Update your base template:

django

```django
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Site{% endblock %}</title>
    
    {% block extra_head %}{% endblock %}
    
    <!-- Humblytics Analytics -->
    {% if ENABLE_ANALYTICS %}
    <script async src="https://app.humblytics.com/hmbl.min.js?id={{ HUMBLYTICS_ID }}"></script>
    {% endif %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
```

#### Option 3: Template include (for multiple base templates)

**Best for:** Projects with multiple base templates (e.g., public site, admin, blog)

1. Create `templates/includes/analytics.html`:

django

```django
{% if not debug %}
<script async src="https://app.humblytics.com/hmbl.min.js?id=YOUR_ID_HERE"></script>
{% endif %}
```

2. Include it in each base template:

django

```django
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Site{% endblock %}</title>
    
    {% include 'includes/analytics.html' %}
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>
```

**Note**: Replace `YOUR_ID_HERE` with your actual project ID from Humblytics.

### 4 · Deploy and verify

1. **Clear Django caches** (if using template caching):

bash

```bash
   python manage.py clear_cache  # If using django-redis or similar
```

2. **Restart your Django server**:

bash

```bash
   # Development
   python manage.py runserver
   
   # Production (example with Gunicorn)
   sudo systemctl restart gunicorn
```

3. **If using static files CDN**, ensure changes are deployed
4. Return to Humblytics and click **Verify Website**
5. Open your live site in a private/incognito window and refresh once
6. Within \~30 seconds you should see a green **Verified** badge and live visitor count

**If verification fails, check:**

**Django-specific issues:**

* You're testing **production** environment, not development with `DEBUG = True`
* Template changes are deployed (check file timestamps on server)
* If using template caching, cache is cleared
* Context processor is registered (for Option 2)
* Environment variable is set correctly in production
* Django server was restarted after changes

**General issues:**

* Script ID matches your project in Humblytics
* View page source (right-click → View Page Source) and search for "humblytics"
* Check Django logs for template errors: `python manage.py check`
* Open Developer Tools (F12) → **Network** tab and search for `hmbl.min.js`
* No ad-blockers or browser extensions are blocking the script

**Debug in Django shell:**

python

```python
python manage.py shell

>>> from django.conf import settings
>>> print(settings.DEBUG)  # Should be False in production
>>> print(getattr(settings, 'HUMBLYTICS_ID', 'Not set'))
```

### 5 · Explore & optimize

* **Dashboard** – see traffic, top pages, and referrers
* **Heatmaps** – auto-generated to reveal click hotspots and scroll depth
* **Experiments** – run A/B tests without extra setup (Experiments → New Test)
