- Quick Start
- Overview
- Plugin Structure
- Available Hooks
- Database Access & Permissions
- Installation & Management
- Complete Examples
- Best Practices
- Troubleshooting
Create your first plugin in 3 minutes:
-
Create the plugin folder:
mkdir -p plugins/my_plugin
-
Create
plugins/my_plugin/plugin.py:class Plugin: name = "my_plugin" version = "1.0.0" def __init__(self): self.hooks = { 'home_page_header': self.show_message, } self.urls = [] def show_message(self, context): return '<div class="alert alert-info">My Plugin is Active!</div>'
-
Enable the plugin:
- Go to Admin Panel → Plugins
- Click Enable next to
my_plugin
-
Test it:
- Visit the home page (
/) and see your message!
- Visit the home page (
The plugin system allows you to extend the scouting app without modifying core code. Plugins can:
- ✅ Add custom UI elements via template hooks
- ✅ Process QR scanner data
- ✅ Modify match data fields (with permissions)
- ✅ Store custom data in the database
- ✅ Add custom API endpoints
- ✅ Be enabled/disabled without code changes
When to use plugins:
- Adding team-specific features
- Custom analytics or visualizations
- Integration with external services
- Experimental features that might be removed later
Minimal structure:
plugins/
└── your_plugin_name/
└── plugin.py # Main plugin class (REQUIRED)
Full structure:
plugins/
└── your_plugin_name/
├── plugin.py # Main plugin class (REQUIRED)
├── requirements.txt # Python dependencies (optional)
├── static/ # JS/CSS files (optional)
│ └── script.js
└── templates/ # HTML templates (optional)
└── widget.html
The Plugin class must:
- Be named exactly
Plugin - Have a
nameattribute (string) - Have a
versionattribute (string, recommended) - Have a
descriptionattribute (string, recommended for user clarity) - Have a
authorattribute (string, recommended) - Have a
requested_permissionsdict (dict, required for transparency) - Have a
hooksdict (can be empty) - Have a
urlslist (can be empty)
Example minimal plugin:
class Plugin:
name = "my_plugin"
version = "1.0.0"
description = "What this plugin does"
author = "Your Name"
requested_permissions = {
"scanner_anchor_patch": [], # List of anchor fields to modify
"data_metrics": [], # List of root data keys to add
"read_only": True, # True if plugin doesn't write to DB
"custom_urls": False, # True if plugin adds API endpoints
"accesses_external_apis": False, # True if calls external services
}
def __init__(self):
self.hooks = {}
self.urls = []Always declare your plugin's permissions using the requested_permissions attribute. This:
- ✅ Informs users what the plugin can do before they enable it
- ✅ Creates trust through transparency
- ✅ Helps administrators assess security risks
- ✅ Documents your plugin's capabilities
Permission fields explained:
scanner_anchor_patch: List of match fields the plugin will modify (e.g.,["start_pos", "comment"])data_metrics: Legacy - list of root data keys (prefer namespaced writes)read_only: Set totrueif plugin never writes to the database (display-only plugins)custom_urls: Set totrueif plugin adds custom API endpointsaccesses_external_apis: Set totrueif plugin calls external services (TBA API, cloud services, etc.)
Hooks are functions that run at specific points in the app. Your plugin registers hooks to inject custom behavior.
| Hook Name | Type | When It Runs | Return Type | Context Available |
|---|---|---|---|---|
home_page_header |
Template | Home page load | HTML string | request |
team_page_header |
Template | Team page load | HTML string | request, team |
team_page_match_row |
Template | Each match row | HTML string | request, match |
scanner_data_process |
Data | QR code scanned | dict or None | qr_data, team_number, event, match_number, scout_name |
scanner_anchor_patch |
Data | Before match save | dict or None | current, qr_data, team_number, event, match_number, scout_name |
Purpose: Add HTML to specific parts of the UI
Example - Add a banner to home page:
class Plugin:
name = "banner_plugin"
def __init__(self):
self.hooks = {
'home_page_header': self.add_banner,
}
def add_banner(self, context):
# context contains: request
return '''
<div class="alert alert-warning">
<strong>Notice:</strong> Playoffs start tomorrow!
</div>
'''Example - Add button to each match row:
def add_match_button(self, context):
# context contains: request, match
match = context.get('match')
if not match:
return ""
return f'''
<button class="btn btn-sm btn-primary"
onclick="alert('Match {match.match_number}')">
Details
</button>
'''Purpose: Process QR scanner data and add custom fields
Example - Extract custom field from QR code:
def process_qr_data(self, context):
# context contains: qr_data, team_number, event, match_number, scout_name
qr_data = context.get('qr_data', {})
# Extract custom field if present
if 'defense_rating' in qr_data:
return {
'defense_rating': int(qr_data['defense_rating']),
'processed_at': datetime.now().isoformat()
}
return None # Return None if nothing to addWhere the data goes:
- Your returned dict is stored at:
Team_Match_Data.data['plugins']['your_plugin_name'] - Automatically namespaced to prevent conflicts
- Cleaned up when plugin is disabled (if cleanup requested)
Purpose: Modify core match fields during scan (REQUIRES PERMISSIONS)
Available anchor fields:
start_pos(int) - Starting positioncomment(str) - Match commentscout_name(str) - Scout namequantifier(str) - 'Quals', 'Playoff', or 'Prac'is_broken(bool) - Robot broken flagis_disabled(bool) - Robot disabled flagis_tipped(bool) - Robot tipped flag
Example - Modify comment and start position:
def patch_anchor_fields(self, context):
# context contains: current, qr_data, team_number, event, match_number, scout_name
current = context.get('current', {})
qr = context.get('qr_data', {})
patch = {}
# Add tag to comment if present in QR
if 'tag' in qr:
base = current.get('comment', '')
patch['comment'] = f"{base} [tag:{qr['tag']}]"[:256]
# Override start position from QR
if 'startPos' in qr:
patch['start_pos'] = int(qr['startPos'])
return patch # Only whitelisted fields are appliedPlugins can write to the database in two ways:
- Automatic (recommended): Return data from
scanner_data_processhook → automatically namespaced - Manual: Use
PluginDBhelpers in custom endpoints → requires explicit namespacing
Control what each plugin can do via plugins/config.json:
{
"enabled": ["my_plugin", "analytics_plugin"],
"permissions": {
"my_plugin": {
"scanner_anchor_patch": ["start_pos", "comment"],
"data_metrics": [],
"read_only": false
},
"analytics_plugin": {
"scanner_anchor_patch": [],
"data_metrics": [],
"read_only": true
}
}
}Permission Fields Explained:
| Field | Type | Purpose | Example |
|---|---|---|---|
scanner_anchor_patch |
list | Anchor fields plugin can modify | ["start_pos", "comment"] |
data_metrics |
list | Root data keys plugin can add (legacy) | ["custom_metric"] |
read_only |
bool | Block all DB writes if true | true for analytics plugins |
QR Code Scanned
↓
Scanner View receives data
↓
Builds anchor fields (team, match, scout_name, etc.)
↓
Calls scanner_data_process hooks
↓
Your plugin returns: {'my_field': 123}
↓
Stored at: data['plugins']['your_plugin']['my_field'] = 123
↓
(Optional) Calls scanner_anchor_patch hooks
↓
Your plugin returns: {'comment': 'Updated comment'}
↓
Only whitelisted fields applied to anchor data
↓
Single DB save with all data
Use the scanner_data_process hook - no manual DB writes needed:
class Plugin:
name = "auto_plugin"
def __init__(self):
self.hooks = {
'scanner_data_process': self.process_data,
}
def process_data(self, context):
qr = context.get('qr_data', {})
# Just return the data you want to store
return {
'custom_score': int(qr.get('custom_score', 0)),
'notes': qr.get('notes', ''),
}
# This automatically goes to:
# Team_Match_Data.data['plugins']['auto_plugin']Benefits:
- ✅ No manual DB code needed
- ✅ Automatically namespaced (no conflicts)
- ✅ Cleaned up when plugin disabled (if requested)
- ✅ Thread-safe (scanner handles the save)
For custom endpoints that need to write data:
from django.urls import path
from django.http import JsonResponse
from plugins.permissions import PluginDB
from datetime import datetime
class Plugin:
name = "manual_plugin"
def __init__(self):
self.urls = [
path('plugins/manual/save/', self.save_data, name='manual_save'),
]
def save_data(self, request):
# Get parameters
team = int(request.POST.get('team'))
event = request.POST.get('event')
match = int(request.POST.get('match'))
scout = request.POST.get('scout')
payload = {
'custom_field': request.POST.get('value'),
'timestamp': datetime.now().isoformat()
}
# Use helper to write namespaced data
try:
obj_id = PluginDB.set_team_match_data(
plugin_name='manual_plugin',
team_number=team,
event=event,
match_number=match,
scout_name=scout,
payload=payload
)
return JsonResponse({'status': 'success', 'id': obj_id})
except PermissionError as e:
return JsonResponse({'error': str(e)}, status=403)Available helpers:
from plugins.permissions import PluginDB
# Write to match data
PluginDB.set_team_match_data(
plugin_name='your_plugin',
team_number=1234,
event='2025cada',
match_number=5,
scout_name='Alice',
payload={'key': 'value'}
)
# Write to pit data
PluginDB.set_team_pit_data(
plugin_name='your_plugin',
team_number=1234,
event='2025cada',
payload={'pit_notes': 'Great robot'}
)To modify core match fields (not just custom data):
1. Configure permissions in plugins/config.json:
{
"enabled": ["field_patcher"],
"permissions": {
"field_patcher": {
"scanner_anchor_patch": ["start_pos", "comment"]
}
}
}2. Implement the hook:
def patch_anchor_fields(self, context):
current = context.get('current', {})
qr = context.get('qr_data', {})
patch = {}
if 'override_start' in qr:
patch['start_pos'] = int(qr['override_start'])
if 'add_note' in qr:
patch['comment'] = current.get('comment', '') + f" | {qr['add_note']}"
return patchSecurity features:
- ✅ Only fields in your permission list are applied
- ✅ Type validation enforced (
int,str,bool) - ✅ All changes audit-logged
- ✅ Invalid values ignored
When disabling a plugin, you can optionally remove its data:
Via Admin Panel:
- Go to Plugins section
- Check "Cleanup data on disable"
- Click Disable
- See count of cleaned records in confirmation
Programmatically:
from plugins import plugin_manager
cleaned = plugin_manager.cleanup_plugin_data('your_plugin')
print(f"Cleaned {cleaned} records")What gets cleaned:
- Data at
Team_Match_Data.data['plugins']['your_plugin'] - Data at
Teams.pit_data['plugins']['your_plugin']
What stays:
- Other plugins' data (untouched)
- Core anchor fields (untouched)
- Rows themselves (only your namespace is removed)
Built-in protections:
- All
PluginDBhelpers usetransaction.atomic - Existing rows locked with
select_for_update()before update - Scanner processes all plugins then saves once (no race between plugins)
- Cleanup locks rows during removal
Best practices:
- Keep transactions short
- Only merge your namespace, don't overwrite entire JSON
- For high-traffic endpoints, add retry logic
- Check plugin enabled status before writes if needed
-
Package your plugin:
cd plugins zip -r my_plugin.zip my_plugin/ -
Upload:
- Go to Admin Panel → Plugins
- Click "Choose File" and select
my_plugin.zip - Click "Upload Plugin"
-
Install dependencies (if needed):
- If your plugin has
requirements.txt - Click "Install Dependencies" button
- If your plugin has
-
Enable:
- Click "Enable" button next to your plugin
-
Copy plugin folder:
cp -r my_plugin plugins/
-
Edit config (optional):
nano plugins/config.json
Add your plugin to
enabledlist -
Restart server:
python manage.py runserver
If your plugin needs extra Python packages:
-
Create
requirements.txtin your plugin folder:requests>=2.28.0 pandas>=1.5.0 -
Install via Admin Panel:
- Click "Install Dependencies" next to your plugin
-
Or install manually:
pip install -r plugins/my_plugin/requirements.txt
Goal: Add custom defense rating field from QR codes
# plugins/defense_tracker/plugin.py
class Plugin:
name = "defense_tracker"
version = "1.0.0"
def __init__(self):
self.hooks = {
'scanner_data_process': self.track_defense,
'team_page_match_row': self.show_rating,
}
self.urls = []
def track_defense(self, context):
"""Extract defense rating from QR code"""
qr = context.get('qr_data', {})
if 'defense_rating' in qr:
try:
rating = int(qr['defense_rating'])
if 1 <= rating <= 5:
return {'defense_rating': rating}
except (ValueError, TypeError):
pass
return None
def show_rating(self, context):
"""Display defense rating in match row"""
match = context.get('match')
if not match:
return ""
rating = match.data.get('plugins', {}).get('defense_tracker', {}).get('defense_rating')
if not rating:
return ""
stars = '★' * rating + '☆' * (5 - rating)
return f'<span title="Defense: {rating}/5">{stars}</span>'Enable it:
{
"enabled": ["defense_tracker"]
}Goal: Automatically add tags to comments based on QR data
Config - Set permissions:
{
"enabled": ["auto_commenter"],
"permissions": {
"auto_commenter": {
"scanner_anchor_patch": ["comment"]
}
}
}Plugin code:
# plugins/auto_commenter/plugin.py
class Plugin:
name = "auto_commenter"
version = "1.0.0"
def __init__(self):
self.hooks = {
'scanner_anchor_patch': self.add_tags,
}
self.urls = []
def add_tags(self, context):
"""Add automatic tags to comments"""
current = context.get('current', {})
qr = context.get('qr_data', {})
base_comment = current.get('comment', '')
tags = []
# Add tags based on QR data
if qr.get('played_defense') == '1':
tags.append('DEFENSE')
if qr.get('tipped') == '1':
tags.append('TIPPED')
if int(qr.get('auto_points', 0)) > 10:
tags.append('STRONG_AUTO')
if tags:
tag_str = ' | '.join(tags)
new_comment = f"{base_comment} [{tag_str}]"[:256]
return {'comment': new_comment}
return NoneGoal: Create a custom analytics endpoint
# plugins/analytics_api/plugin.py
from django.urls import path
from django.http import JsonResponse
from teams.models import Team_Match_Data
class Plugin:
name = "analytics_api"
version = "1.0.0"
def __init__(self):
self.hooks = {}
self.urls = [
path('plugins/analytics/team/<int:team_num>/',
self.team_stats,
name='analytics_team_stats'),
]
def team_stats(self, request, team_num):
"""Return custom analytics for a team"""
event = request.GET.get('event', 'testing')
matches = Team_Match_Data.objects.filter(
team_number=team_num,
event=event
)
if not matches.exists():
return JsonResponse({'error': 'No data'}, status=404)
# Calculate custom stats
total_matches = matches.count()
avg_auto = sum(m.data.get('auto_points', 0) for m in matches) / total_matches
return JsonResponse({
'team': team_num,
'event': event,
'matches_played': total_matches,
'avg_auto_points': round(avg_auto, 2),
})Use it:
GET /plugins/analytics/team/1234/?event=2025cada
- Plugin name: lowercase with underscores (
my_plugin) - URL prefix:
plugins/your-plugin/ - Template IDs:
your-plugin-element-id
def your_hook(self, context):
try:
# Your logic
return result
except Exception as e:
# Log but don't crash
print(f"Error in {self.name}: {e}")
return None # or "" for template hooks- Always use namespaced keys via
scanner_data_processhook orPluginDBhelpers - Don't write directly to models in hooks
- Keep payload sizes reasonable (<1KB recommended)
- Template hooks should return quickly (<50ms)
- Avoid heavy computation in hooks
- Cache expensive calculations
- Use database indexes for custom queries
- Validate all user input
- Escape HTML in template returns
- Use Django's template system for complex HTML
- Don't expose sensitive data in templates
# Test your hook locally
plugin = Plugin()
context = {'qr_data': {'test': '123'}}
result = plugin.process_data(context)
print(result) # Should return your expected dataBe transparent about what your plugin does:
- Declare all permissions accurately in
requested_permissions - Document external API calls and data collection
- Use descriptive names and clear descriptions
- Provide source code or detailed documentation
- Test thoroughly before distributing
Security best practices:
- Never store API keys or passwords in plugin code
- Validate and sanitize all user input
- Use Django's built-in security features
- Limit network requests to necessary operations only
- Use HTTPS for external API calls
Before installing a plugin:
- Review permissions displayed during upload
- Check source code if available (look for suspicious patterns)
- Verify author - is this from a trusted source?
- Test in development before deploying to production
- Monitor behavior after enabling - check logs for unexpected activity
Red flags to watch for:
- Requests excessive permissions (modifying many anchor fields)
- Accesses external APIs without clear justification
- Obfuscated or difficult-to-read code
- No description or author information
- Asks for permissions it doesn't seem to need
Permission safety levels:
| Permission | Risk Level | Notes |
|---|---|---|
read_only: true |
✅ Low | Cannot modify data |
| Display-only hooks | ✅ Low | Just adds UI elements |
scanner_data_process |
Adds namespaced data (easy to clean) | |
scanner_anchor_patch |
🔴 High | Modifies core match fields |
custom_urls: true |
Adds API endpoints (review code) | |
accesses_external_apis: true |
🔴 High | May leak data externally |
When you upload a plugin, the system automatically shows:
- Plugin name, version, author, description
- All requested permissions with warnings
- Whether it has custom API endpoints
- Whether it requires additional dependencies
- Whether it accesses external APIs
The plugin is uploaded but DISABLED by default - you must manually enable it after review.
Check:
- Is plugin folder in
plugins/? - Does it have
plugin.pywith aPluginclass? - Is it enabled in
plugins/config.json? - Did you restart the server after adding it?
Debug:
# Check if plugin is discovered
python manage.py shell
>>> from plugins import plugin_manager
>>> plugin_manager.list_available_plugins()
['your_plugin', 'hello_world', ...]
>>> plugin_manager._enabled_names
['your_plugin', ...] # Should include your pluginCheck:
- Is hook name spelled correctly?
- Is hook function registered in
self.hooksdict? - Does function return correct type (str for templates, dict for data)?
Debug:
# In your hook
def your_hook(self, context):
print(f"HOOK CALLED: {context}") # Should appear in server logs
return resultCheck:
- Is plugin name in
permissionssection ofconfig.json? - Are field names spelled correctly?
- For
read_only=true, remove DB write calls
Debug:
>>> from plugins import plugin_manager
>>> plugin_manager.get_anchor_patch_fields('your_plugin')
['start_pos', 'comment'] # Should show your allowed fieldsCheck:
- Hook returns a dict (not None)?
- Data structure is JSON-serializable?
- For anchor patches, fields are in permissions whitelist?
Debug:
# Check saved data
>>> from teams.models import Team_Match_Data
>>> match = Team_Match_Data.objects.first()
>>> match.data.get('plugins', {}).get('your_plugin')
{'your_field': 'value'} # Your data should be hereCheck:
- Is
requirements.txtin plugin folder root? - Are package names valid?
- Does server have internet access?
Manual install:
pip install -r plugins/your_plugin/requirements.txt- Example plugin: See
plugins/hello_world/for a working example - Template plugin: See
plugins/example_plugin_template.pyfor comprehensive template - Models: See
teams/models.pyfor data structure - Config validation: See
scanner/validation.pyfor field types
Need help? Check the server logs for detailed error messages:
tail -f logs/django.log # Or wherever your logs are