Skip to main content
Server-side script loading package for Python applications, providing secure, cached script loading with Django template tag integration.

Django Integration

A Django package to fetch and render scripts from a remote URL with template tag integration and caching support.

Installation

Install the package via pip:
pip install adunblock-server-tag-django
Every rendered <script> tag must include a data-code attribute set to your Account ID (verification code). AdUnblock uses this value to verify that the script is running on your registered domain. Find your Account ID at the top of your AdUnblock dashboard.
Add the server_tag app to your INSTALLED_APPS in your Django settings.py:
INSTALLED_APPS = [
    # ... other apps
    'server_tag',
]

Cache Configuration

Configure caching in your settings.py (recommended for production):

Redis Cache (Production)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
    }
}

Local Memory Cache (Development)

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'unique-snowflake',
    }
}

Basic Usage

In your view, pass the Account ID / verification code via the template context:
# views.py
def home(request):
    return render(request, 'home.html', {
        'server_tag_attrs': {'data-code': 'YOUR_ACCOUNT_ID'},
    })
Then in your Django template, load the server_tag_tags and use the server_tag tag with the script_attributes argument:
{% load server_tag_tags %}

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  {% server_tag "https://public.adunblocker.com/api/vendor_scripts" script_attributes=server_tag_attrs %}
</head>
<body>
  <h1>My Page</h1>
</body>
</html>

Custom Rendering

You can provide a custom Python function to the render_script parameter to customize how script tags are rendered:

Create Custom Template Tag

# my_app/templatetags/custom_tags.py
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag
def custom_script_renderer(scripts):
    from django.utils.html import escape
    script_tags = [f'<script src="{escape(src)}" defer></script>' for src in scripts]
    return mark_safe('\n'.join(script_tags))

Use Custom Renderer in Template

{% load server_tag_tags %}
{% load custom_tags %}

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  {% server_tag "https://public.adunblocker.com/api/vendor_scripts" render_script=custom_script_renderer %}
</head>
<body>
  <h1>My Page</h1>
</body>
</html>

Expected Remote Response Format

The remote URL should return a JSON response in this format:
[
  "https://example.com/script1.js",
  "https://example.com/script2.js"
]

Django Features

  • Template Tag Integration: Easy-to-use Django template tag
  • HTTP Client: Uses requests library for reliable HTTP operations
  • Caching: Built-in Django cache integration with configurable TTL
  • Error Handling: Graceful error handling with fallback to empty arrays
  • Security: XSS protection with proper HTML escaping
  • Django Integration: Proper Django app structure with apps.py

Advanced Usage

Template Tag with Cache Control

{% load server_tag_tags %}

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  {% server_tag "https://public.adunblocker.com/api/vendor_scripts" cache_timeout=600 %}
</head>
<body>
  <h1>My Page</h1>
</body>
</html>

Conditional Script Loading

{% load server_tag_tags %}

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  {% if user.is_authenticated %}
    {% server_tag "https://public.adunblocker.com/api/vendor_scripts" %}
  {% else %}
    {% server_tag "https://public.adunblocker.com/api/vendor_scripts" %}
  {% endif %}
</head>
<body>
  <h1>My Page</h1>
</body>
</html>

Using in Class-Based Views

from django.views.generic import TemplateView
from django.template.loader import render_to_string

class MyView(TemplateView):
    template_name = 'my_template.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # You can also use the server_tag functionality in views
        context['page_title'] = 'My Custom Page'

        return context

Configuration Options

The Django package supports several configuration options:

Settings Configuration

You can configure default settings in your settings.py:
# Optional: Configure default cache timeout
SERVER_TAG_DEFAULT_TIMEOUT = 300  # 5 minutes

# Optional: Configure default HTTP timeout
SERVER_TAG_HTTP_TIMEOUT = 10  # 10 seconds

# Optional: Configure retry attempts
SERVER_TAG_RETRY_ATTEMPTS = 3

Template Tag Parameters

The server_tag template tag accepts these parameters:
ParameterTypeDefaultDescription
remote_urlstringRequiredURL to fetch script configuration from
cache_timeoutnumber300Cache duration in seconds
script_attributesdictNoneAttributes applied to every generated <script> tag. Must include 'data-code': YOUR_ACCOUNT_ID.
render_scriptfunctionNoneCustom script rendering function

Error Handling

The Django package includes robust error handling:
# In your Django settings, you can configure logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': 'server_tag_errors.log',
        },
    },
    'loggers': {
        'server_tag': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

Security Considerations

  • URL Validation: Only HTTP and HTTPS URLs are allowed
  • XSS Protection: All output is properly escaped using Django’s built-in functions
  • Error Handling: Failed requests don’t break template rendering
  • Caching: Reduces load on remote servers and improves performance

Performance Tips

  1. Use Redis: Configure Redis caching for production environments
  2. Cache Warming: Pre-warm caches during deployment
  3. Error Monitoring: Monitor failed requests and adjust retry logic
  4. CDN Usage: Use CDN URLs for better performance

Requirements

  • Python 3.8 or higher
  • Django 3.2 or higher
  • requests 2.25.0 or higher

Common Patterns

Base Template with Server Tags

<!-- base.html -->
{% load server_tag_tags %}

<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}My Site{% endblock %}</title>
  {% server_tag "https://public.adunblocker.com/api/vendor_scripts" %}
  {% block extra_scripts %}{% endblock %}
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

Page-Specific Scripts

<!-- specific_page.html -->
{% extends "base.html" %}
{% load server_tag_tags %}

{% block extra_scripts %}
  {% server_tag "https://public.adunblocker.com/api/vendor_scripts" %}
{% endblock %}

{% block content %}
  <h1>Specific Page Content</h1>
{% endblock %}

Next Steps

Test Implementation

Test your Django integration with our Chrome extension

Node.js Integration

Learn about Node.js server-side integration