### Start Redis Server
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Start the Redis server. This command is used after installing Redis to ensure the database is running.
```bash
redis-server
```
--------------------------------
### Install Redis
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Instructions for installing Redis on different operating systems. Redis is a required prerequisite for the development environment.
```bash
# macOS: brew install redis
# Ubuntu: sudo apt-get install redis-server
# Windows: Download from [Redis website](https://redis.io/download)
```
--------------------------------
### Install Wagtail integration
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Use this command to install the package with Wagtail support enabled.
```bash
pip install djinsight[wagtail]
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Install the project's development dependencies using pip. The `.[dev]` flag installs optional dependencies required for development.
```bash
pip install -e .[dev]
```
--------------------------------
### Configure djinsight in Django
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Setup installation and settings for database-only or high-traffic Redis/Celery modes.
```python
# Install djinsight
# pip install djinsight
# pip install djinsight[mcp] # For MCP/AI integration
# pip install djinsight[redis] # For Redis backend
# pip install djinsight[celery] # For async processing
# pip install djinsight[wagtail] # For Wagtail dashboard
# settings.py - Basic configuration (database-only mode)
INSTALLED_APPS = [
# ... your apps
'djinsight',
'djinsight.wagtail', # Optional: for Wagtail admin dashboard
]
DJINSIGHT = {
'ENABLE_TRACKING': True,
'USE_REDIS': False,
'USE_CELERY': False,
}
# settings.py - High-traffic configuration with Redis and Celery
DJINSIGHT = {
'ENABLE_TRACKING': True,
'USE_REDIS': True,
'USE_CELERY': True,
'REDIS_HOST': 'localhost',
'REDIS_PORT': 6379,
'REDIS_DB': 0,
'REDIS_URL': None, # Alternative: 'redis://localhost:6379/0'
'REDIS_KEY_PREFIX': 'djinsight:pageview',
'ADMIN_ONLY': False, # Restrict stats access to staff users
'TRACK_ANONYMOUS': True,
'TRACK_AUTHENTICATED': True,
'RETENTION_DAYS': 365,
'PROCESS_BATCH_SIZE': 100,
'PROCESS_MAX_RECORDS': 10000,
'CLEANUP_DAYS_TO_KEEP': 90,
}
# urls.py
from django.urls import include, path
urlpatterns = [
path('djinsight/', include('djinsight.urls')),
]
# Run migrations
# python manage.py migrate
```
--------------------------------
### Build and Install Package
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Build source and wheel distributions of the package using `python -m build`. Also includes commands to check the package integrity and install it locally for testing.
```bash
# Build source and wheel distributions
python -m build
# Check the package
python setup.py check
# Install locally for testing
pip install -e .
```
--------------------------------
### Install Djinsight v0.3.5
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Command to install the specific version 0.3.5 of Djinsight using pip.
```bash
pip install djinsight==0.3.5
```
--------------------------------
### Install djinsight with MCP Support
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Install djinsight with the 'mcp' extra to enable integration with Claude Desktop's MCP (Messaging Communication Protocol).
```bash
pip install djinsight[mcp]
```
--------------------------------
### Install djinsight
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Install the djinsight package using pip. This is the initial step for integrating analytics into your Django project.
```bash
pip install djinsight
```
--------------------------------
### Create and Activate Virtual Environment
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Create a Python virtual environment to isolate project dependencies. Activate it before installing packages. The activation command differs between operating systems.
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
--------------------------------
### Start Celery Workers and Beat
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Run Celery workers and the beat scheduler to handle asynchronous tasks for djinsight when Redis and Celery are enabled.
```bash
celery -A your_project worker -l info
```
```bash
celery -A your_project beat -l info
```
--------------------------------
### Async Database Provider for Async Views
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Demonstrates using the AsyncDatabaseProvider within an asynchronous Django view to fetch statistics. Requires an async Django setup.
```python
from djinsight.providers.database import DatabaseProvider, AsyncDatabaseProvider
from djinsight.registry import ProviderRegistry
async def my_async_view(request):
async_provider = AsyncDatabaseProvider()
stats = await async_provider.get_stats('blog.article', 42)
return JsonResponse(stats)
```
--------------------------------
### Create PageViewLog Entry
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Example of creating a PageViewLog entry using Django's ORM. This test demonstrates how to interact with the PageViewLog model.
```python
from django.test import TestCase
from djinsight.models import PageViewLog
class PageViewLogTest(TestCase):
def test_create_page_view_log(self):
log = PageViewLog.objects.create(
page_id=1,
content_type="tests.testpage",
url="/test-page/"
)
self.assertEqual(log.page_id, 1)
```
--------------------------------
### Universal Stats Tag Usage
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Examples of using the universal stats tag with different metrics, periods, and output formats.
```django
{% stats metric="views" period="today" output="text" %}
{% stats metric="unique_views" period="week" output="chart" %}
{% stats metric="views" period="custom" start_date=start end_date=end output="json" %}
```
--------------------------------
### Get Site-Wide Analytics Overview
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Aggregates analytics data across all tracked content types for a high-level site overview.
```python
from djinsight.mcp.tools.cross_model import get_site_overview
result = get_site_overview()
# Returns:
{
"total_views": 125000,
"total_unique_views": 67500,
"tracked_objects": 1250,
"by_content_type": [
{
"content_type": "blog.article",
"total_views": 85000,
"unique_views": 45000,
"object_count": 450
},
{
"content_type": "products.product",
"total_views": 35000,
"unique_views": 19500,
"object_count": 680
},
{
"content_type": "pages.page",
"total_views": 5000,
"unique_views": 3000,
"object_count": 120
}
]
}
```
--------------------------------
### Implement Custom Widget and Chart Renderers
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Create custom renderer classes by extending BaseRenderer and DefaultChartRenderer. Implement the render method to define custom output formats for widgets and charts. This example shows custom text and chart rendering logic.
```python
# myapp/renderers.py
from djinsight.renderers import BaseRenderer, DefaultChartRenderer
class CustomWidgetRenderer(BaseRenderer):
def render(self) -> str:
data = self.get_data()
if not data:
return ""
if self.output == "text":
return f"{data.get('total_views', 0)}"
elif self.output == "chart":
chart_renderer = CustomChartRenderer(
data=data,
chart_type=self.kwargs.get('chart_type', 'line'),
chart_color=self.kwargs.get('chart_color'),
)
return chart_renderer.render()
return super().render()
```
```python
class CustomChartRenderer(DefaultChartRenderer):
def render(self) -> str:
# Custom chart rendering logic
return f'''
'''
```
--------------------------------
### Celery Configuration and Schedules
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Configures Celery for background tasks, including setting up beat schedules for processing page views, generating summaries, and cleaning up data. Ensure Celery is installed and configured.
```python
from celery import Celery
from celery.schedules import crontab
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.beat_schedule = {
'process-page-views': {
'task': 'djinsight.tasks.process_page_views_task',
'schedule': 10.0, # Every 10 seconds
},
'generate-daily-summaries': {
'task': 'djinsight.tasks.generate_daily_summaries_task',
'schedule': crontab(minute='*/10'), # Every 10 minutes
},
'cleanup-old-data': {
'task': 'djinsight.tasks.cleanup_old_data_task',
'schedule': crontab(hour=1, minute=0), # Daily at 1:00 AM
},
}
```
--------------------------------
### Get Hourly Traffic Pattern
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Analyzes traffic distribution by hour to identify peak viewing times for a specific content object.
```python
from djinsight.mcp.tools.behavior import get_hourly_pattern
result = get_hourly_pattern(
content_type="blog.article",
object_id=42, # Optional: None for all articles
period="week"
)
# Returns:
{
"content_type": "blog.article",
"object_id": 42,
"period": "week",
"total_views": 1250,
"peak_hour": "14:00",
"hours": [
{"hour": 0, "label": "00:00", "views": 12},
{"hour": 1, "label": "01:00", "views": 8},
# ... all 24 hours
{"hour": 14, "label": "14:00", "views": 125}, # Peak
# ... more hours
{"hour": 23, "label": "23:00", "views": 45}
]
}
```
--------------------------------
### Conventional Commit Messages
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Examples of conventional commit messages used for tracking changes. These messages follow a `type: description` format for clarity.
```bash
feat: add new template tag for analytics widget
fix: resolve Redis connection timeout issue
docs: update installation instructions
test: add tests for PageViewLog model
refactor: improve error handling in views
```
--------------------------------
### Database Provider: Record and Get Stats
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Uses the synchronous DatabaseProvider to record page views and retrieve statistics for a given content type and object ID. Ensure the provider is correctly configured in settings.
```python
from djinsight.providers.database import DatabaseProvider, AsyncDatabaseProvider
from djinsight.registry import ProviderRegistry
provider = ProviderRegistry.get_provider()
event_data = {
'content_type': 'blog.article',
'object_id': 42,
'url': '/blog/my-article/',
'session_key': 'abc123xyz',
'ip_address': '192.168.1.1',
'user_agent': 'Mozilla/5.0...',
'referrer': 'https://google.com',
'timestamp': 1710936000, # Unix timestamp
'is_unique': True,
}
result = provider.record_view(event_data)
# Returns: {'success': True, 'event_id': 123, 'stats': {'total_views': 10, 'unique_views': 5}}
stats = provider.get_stats('blog.article', 42)
# Returns: {'total_views': 156, 'unique_views': 89, 'first_viewed_at': '...', 'last_viewed_at': '...'}
is_unique = provider.check_unique_view('session_key_123', 'blog.article', 42)
```
--------------------------------
### Get Device Breakdown Analytics
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves the distribution of page views across different device types for a specific content object.
```python
from djinsight.mcp.tools.behavior import get_device_breakdown
result = get_device_breakdown(
content_type="blog.article",
object_id=42, # Optional: None for all articles
period="month"
)
# Returns:
{
"content_type": "blog.article",
"object_id": 42,
"period": "month",
"total_views": 2500,
"devices": [
{"device": "desktop", "views": 1500, "percentage": 60.0},
{"device": "mobile", "views": 875, "percentage": 35.0},
{"device": "tablet", "views": 100, "percentage": 4.0},
{"device": "bot", "views": 25, "percentage": 1.0}
]
}
```
--------------------------------
### Get Top 10 Articles by Total Views
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves the top 10 articles based on their total view count. Specify 'unique_views' for unique view counts.
```python
result = get_top_pages(
content_type="blog.article",
limit=10,
metric="total_views" # or "unique_views"
)
```
--------------------------------
### Get Trending Pages by Growth Direction
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Identifies pages with the biggest growth or decline compared to the previous period. Specify 'up' for growing or 'down' for declining pages.
```python
from djinsight.mcp.tools.trends import get_trending_pages
# Get trending up pages
result = get_trending_pages(
content_type="blog.article",
period="week",
direction="up", # 'up' for growing, 'down' for declining
limit=10
)
```
```python
# Get declining pages
declining = get_trending_pages(
content_type="blog.article",
period="month",
direction="down",
limit=5
)
```
--------------------------------
### MCP Tool: Get Top Pages
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves a list of top-performing pages, sorted by total or unique views for a given content type, using the MCP protocol. This function is useful for identifying popular content.
```python
from djinsight.mcp.tools.basic import get_top_pages
```
--------------------------------
### Run Django Migrations
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
After configuring djinsight, run Django migrations to set up the necessary database tables for tracking analytics data.
```bash
python manage.py migrate
```
--------------------------------
### Get Page Stats
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves statistics for a specific object. This endpoint can be used to get view counts and other analytics data.
```APIDOC
## POST /djinsight/page-stats/
### Description
Retrieves statistics for a specific object, such as total and unique views. Requires authentication if ADMIN_ONLY is set to True in settings.
### Method
POST
### Endpoint
/djinsight/page-stats/
### Parameters
#### Request Body
- **page_id** (integer) - Required - The ID of the page or object.
- **content_type** (string) - Required - The Django content type of the object (e.g., "blog.article").
### Request Example
```json
{
"page_id": 42,
"content_type": "blog.article"
}
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the status of the request (e.g., "success").
- **page_id** (integer) - The ID of the page or object.
- **content_type** (string) - The Django content type of the object.
- **total_views** (integer) - Total number of views.
- **unique_views** (integer) - Number of unique views.
- **first_viewed_at** (string) - Timestamp of the first view in ISO format.
- **last_viewed_at** (string) - Timestamp of the last view in ISO format.
#### Response Example
```json
{
"status": "success",
"page_id": 42,
"content_type": "blog.article",
"total_views": 1567,
"unique_views": 892,
"first_viewed_at": "2024-01-15T10:30:00Z",
"last_viewed_at": "2024-03-20T14:22:00Z"
}
```
```
--------------------------------
### Get Top Referrer Domains for Page Views
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves top referrer domains for page views, grouped by domain. Set object_id to None to get stats for all articles.
```python
from djinsight.mcp.tools.referrers import get_referrer_stats
result = get_referrer_stats(
content_type="blog.article",
object_id=42, # Optional: None for all articles
period="month",
limit=20
)
```
--------------------------------
### Update Model Code (Remove Mixin)
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Example showing how to update a Django model by removing the PageViewStatisticsMixin.
```python
# OLD
from djinsight.models import PageViewStatisticsMixin
class Article(models.Model, PageViewStatisticsMixin):
title = models.CharField(max_length=200)
# NEW - clean!
class Article(models.Model):
title = models.CharField(max_length=200)
```
--------------------------------
### Run Djinsight Migrations
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Command to apply new database migrations for Djinsight v0.3.5.
```bash
python manage.py migrate djinsight
```
--------------------------------
### Clone djinsight Repository
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Clone the djinsight repository and navigate into the project directory. This is the first step for setting up the development environment.
```bash
git clone https://github.com/krystianmagdziarz/djinsight.git
cd djinsight
```
--------------------------------
### Consolidated Settings Structure
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Djinsight now uses a `DJINSIGHT = {}` dictionary for configuration, offering a cleaner structure while maintaining backward compatibility with `DJINSIGHT_*` settings.
```python
DJINSIGHT = {
'TRACK_ANONYMOUS_USERS': False,
'ANONYMOUS_USER_TRACKING_COOKIE_NAME': 'djinsight_anonymous_id',
}
```
--------------------------------
### Build and Upload to PyPI
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Build the package distributions and upload them to PyPI using `twine`. This command is used for releasing new versions of the package.
```bash
python -m build
twine upload dist/*
```
--------------------------------
### Initialize Daily Views Chart with Chart.js
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/djinsight/wagtail/templates/djinsight/wagtail/reports/partials/_chart.html
Uses Chart.js to render a line chart with data passed from Django context variables. Requires the Chart.js library to be loaded in the environment.
```javascript
(function() { var ctx = document.getElementById('dji-daily-chart'); if (ctx && typeof Chart !== 'undefined') { new Chart(ctx, { type: 'line', data: { labels: {{ chart_labels_json|safe }}, datasets: [ { label: '{% trans "Views" %}', data: {{ chart_views_json|safe }}, borderColor: '#007bff', backgroundColor: 'rgba(0,123,255,0.1)', fill: true, tension: 0.3, pointRadius: 2, }, { label: '{% trans "Unique" %}', data: {{ chart_unique_json|safe }}, borderColor: '#28a745', backgroundColor: 'rgba(40,167,69,0.1)', fill: true, tension: 0.3, pointRadius: 2, } ] }, options: { responsive: true, maintainAspectRatio: false, interaction: { mode: 'index', intersect: false }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } }, x: { ticks: { maxTicksAutoSkip: true, maxRotation: 45 } } }, plugins: { legend: { position: 'top' } } } }); } })();
```
--------------------------------
### Djinsight Settings Structure (v0.1.x)
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Older versions used many individual settings variables for configuration.
```python
DJINSIGHT_ENABLE_TRACKING = True
DJINSIGHT_ADMIN_ONLY = False
DJINSIGHT_REDIS_HOST = 'localhost'
# ... many separate settings
```
--------------------------------
### Get page statistics via REST API
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieve view statistics for a specific object. Authentication is required if ADMIN_ONLY is set to True.
```bash
curl -X POST http://localhost:8000/djinsight/page-stats/ \
-H "Content-Type: application/json" \
-H "Cookie: sessionid=your-session-id" \
-d '{
"page_id": 42,
"content_type": "blog.article"
}'
```
--------------------------------
### Backup Djinsight Database
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Command to create a JSON backup of the djinsight app's data before migration.
```bash
python manage.py dumpdata djinsight > djinsight_backup.json
```
--------------------------------
### Djinsight Settings Structure (v0.3.5)
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
v0.3.5 consolidates settings into a single DJINSIGHT dictionary, offering more flexibility for async/sync modes and extensibility.
```python
DJINSIGHT = {
# Core settings
'ENABLE_TRACKING': True,
'ADMIN_ONLY': False,
# Synchronous mode (no Redis/Celery needed)
'USE_REDIS': False,
'USE_CELERY': False,
# Or async mode with Redis + Celery:
# 'USE_REDIS': True,
# 'USE_CELERY': True,
# 'REDIS_HOST': 'localhost',
# 'REDIS_PORT': 6379,
# 'REDIS_URL': None, # or 'redis://localhost:6379/0' for cloud
# 'REDIS_DB': 0,
# 'REDIS_PASSWORD': None,
# Extensibility
'WIDGET_RENDERER': 'djinsight.renderers.DefaultWidgetRenderer',
'CHART_RENDERER': 'djinsight.renderers.DefaultChartRenderer',
'PROVIDER_CLASS': 'djinsight.providers.redis.RedisProvider',
# Tracking preferences
'TRACK_ANONYMOUS': True,
'TRACK_AUTHENTICATED': True,
'TRACK_STAFF': True,
# Data retention
'RETENTION_DAYS': 365,
'SUMMARY_RETENTION_DAYS': 730,
}
```
--------------------------------
### Configure djinsight in settings.py
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Add djinsight to your Django project's INSTALLED_APPS and configure its settings. Key options include enabling tracking and choosing backend services like Redis or Celery.
```python
INSTALLED_APPS += ['djinsight']
DJINSIGHT = {
'ENABLE_TRACKING': True,
'USE_REDIS': False,
'USE_CELERY': False,
}
```
--------------------------------
### Run Djinsight Data Migration Command
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Optional command to migrate data, with options for dry run and batch size.
```bash
# Dry run first
python manage.py migrate_to_v2 --dry-run
# Actual migration
python manage.py migrate_to_v2
# With custom batch size
python manage.py migrate_to_v2 --batch-size=500
```
--------------------------------
### Create Git Tag for Release
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Create an annotated Git tag for a new release and push it to the remote repository. This is part of the release process.
```bash
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0
```
--------------------------------
### Get Unique Views for Custom Period
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves unique views for a specified article within a custom date range. Requires Django's timezone and datetime modules.
```python
from django.utils.timezone import now
from datetime import timedelta
start_date = now() - timedelta(days=14)
unique_views = StatsQueryMixin.get_unique_views_period(article, start_date)
```
--------------------------------
### Migrating to Djinsight v2
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Execute the `migrate_to_v2` management command to automatically migrate your data from older Djinsight versions to the new schema. Supports dry-run and batch size options.
```python
python manage.py migrate_to_v2 --dry-run
```
```python
python manage.py migrate_to_v2 --batch-size=1000
```
--------------------------------
### Get Period Statistics for Articles
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Fetches view statistics for a specific time period with a daily breakdown. Supports predefined periods like 'today', 'week', 'month', 'year', or a 'custom' date range.
```python
from djinsight.mcp.tools.periods import get_period_stats
# Get weekly stats
result = get_period_stats(
content_type="blog.article",
object_id=42,
period="week" # 'today', 'week', 'month', 'year', 'custom'
)
```
```python
# Custom date range
result = get_period_stats(
content_type="blog.article",
object_id=42,
period="custom",
start_date="2024-01-01",
end_date="2024-03-31"
)
```
--------------------------------
### Django Management Commands: Migration
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Runs the migration command to upgrade Djinsight from v0.1.x to v0.2.0+. Use `--dry-run` to preview changes before execution.
```bash
# Migrate from djinsight v0.1.x to v0.2.0+
python manage.py migrate_to_v2 --dry-run # Preview changes
python manage.py migrate_to_v2 --batch-size=1000 # Execute migration
```
--------------------------------
### MCP Tool: Get Page Stats
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves page view statistics for a specific object using the MCP protocol, intended for AI agent queries. Requires the content type and object ID.
```python
# MCP tool function signature
from djinsight.mcp.tools.basic import get_page_stats
result = get_page_stats(
content_type="blog.article",
object_id=42
)
# Returns:
{
"content_type": "blog.article",
"object_id": 42,
"object": "My Article Title", # str() of the object
"total_views": 1567,
"unique_views": 892,
"first_viewed_at": "2024-01-15T10:30:00+00:00",
"last_viewed_at": "2024-03-20T14:22:00+00:00"
}
```
--------------------------------
### Custom Backends Configuration
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
djinsight allows you to swap out components like the data provider or widget renderer by specifying custom class paths in your settings.
```python
DJINSIGHT = {
'PROVIDER_CLASS': 'myapp.providers.CustomProvider',
'WIDGET_RENDERER': 'myapp.renderers.CustomRenderer',
}
```
--------------------------------
### Configure djinsight Settings
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Define tracking behavior, storage backend, and processing mode in the Django settings dictionary.
```python
DJINSIGHT = {
'ENABLE_TRACKING': True,
'USE_REDIS': False, # Direct database writes
'USE_CELERY': False, # No background processing
}
```
--------------------------------
### Configure High Traffic Settings
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
For high-traffic sites, enable Redis and Celery in djinsight's settings for asynchronous processing. Specify Redis host if necessary.
```python
DJINSIGHT = {
'ENABLE_TRACKING': True,
'USE_REDIS': True,
'USE_CELERY': True,
'REDIS_HOST': 'localhost',
}
```
--------------------------------
### Configure Claude Desktop for djinsight MCP
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Add djinsight as an MCP server in your Claude Desktop configuration file. This allows Claude to communicate with your Django application's analytics.
```json
{
"mcpServers": {
"djinsight": {
"command": "python",
"args": ["-m", "djinsight.mcp"],
"env": {
"DJANGO_SETTINGS_MODULE": "your_project.settings"
}
}
}
}
```
--------------------------------
### Create Migration for Mixin Fields
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Generate and apply migrations to remove legacy mixin fields from the database.
```bash
python manage.py makemigrations yourapp --name remove_pageview_mixin_fields
python manage.py migrate
```
--------------------------------
### Run Pytest Suite
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Execute the test suite using pytest. Various flags are available for running all tests, with coverage, specific files, or verbose output.
```bash
# Run all tests
pytest
# Run with coverage
pytest --cov=djinsight
# Run specific test file
pytest djinsight/tests/test_models.py
# Run with verbose output
pytest -v
```
--------------------------------
### Include djinsight URLs
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/README.md
Add djinsight's URLs to your project's main urls.py file to make its features accessible.
```python
urlpatterns = [
path('djinsight/', include('djinsight.urls')),
]
```
--------------------------------
### Generate Chart with Chart.js
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/djinsight/templates/djinsight/charts/default_chart.html
This JavaScript code initializes a chart using Chart.js. It dynamically fetches chart data, type, and color from template variables. Ensure the target canvas element exists and the chart data is properly formatted.
```javascript
(function() { const chartId = 'djinsight-chart-{{ chart_id|default:"default" }}'; const ctx = document.getElementById(chartId); if (!ctx) return; const chartData = {{ chart_data|safe }}; const chartType = '{{ chart_type|default:"line" }}'; const chartColor = '{{ chart_color|default:"#007bff" }}'; const labels = chartData.map(item => item.label || item.date); const data = chartData.map(item => item.count || 0); const config = { type: chartType, data: { labels: labels, datasets: [{ label: 'Views', data: data, backgroundColor: chartType === 'bar' ? chartColor : chartColor + '20', borderColor: chartColor, borderWidth: 2, fill: chartType === 'line', tension: 0.4 }] }, options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { display: false }, tooltip: { mode: 'index', intersect: false, } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } } }; new Chart(ctx, config); })();
```
--------------------------------
### Claude Desktop MCP Server Configuration
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Configures Claude Desktop to use Djinsight's MCP server for AI agent queries. This involves setting up the command, arguments, and environment variables in the `claude_desktop_config.json` file.
```json
# Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json)
{
"mcpServers": {
"djinsight": {
"command": "python",
"args": ["-m", "djinsight.mcp"],
"env": {
"DJANGO_SETTINGS_MODULE": "myproject.settings"
}
}
}
}
```
--------------------------------
### Compare Current Period Statistics Against Previous
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Compares current period statistics against the previous period to calculate growth rates and view deltas. Supports 'today', 'week', 'month', 'year' periods.
```python
from djinsight.mcp.tools.periods import compare_periods
result = compare_periods(
content_type="blog.article",
object_id=42,
period="week" # 'today', 'week', 'month', 'year'
)
```
--------------------------------
### Record a page view via REST API
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Use this endpoint to log a page view event. Requires a JSON payload with object identification and metadata.
```bash
curl -X POST http://localhost:8000/djinsight/record-view/ \
-H "Content-Type: application/json" \
-d '{
"object_id": 42,
"content_type": "blog.article",
"url": "/blog/my-article/",
"referrer": "https://google.com",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}'
```
--------------------------------
### Django Management Commands
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Executes Djinsight's management commands for processing views, generating summaries, and cleaning up the database. Supports various command-line arguments for customization.
```bash
# Process page views from Redis to database
python manage.py process_pageviews
python manage.py process_pageviews --batch-size=500 --max-records=10000
# Generate daily view summaries
python manage.py generate_summaries
python manage.py generate_summaries --days-back=30
# Cleanup old page view events
python manage.py cleanup_pageviews
python manage.py cleanup_pageviews --days-to-keep=60
```
--------------------------------
### DatabaseProvider API
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Provides synchronous and asynchronous methods for recording page views and retrieving statistics directly from the database.
```APIDOC
## DatabaseProvider API
### Description
Synchronous database provider for direct page view recording without Redis/Celery dependencies.
### Methods
#### `record_view(event_data)`
Records a single page view event.
- **event_data** (dict) - Required - Dictionary containing view details like `content_type`, `object_id`, `url`, `session_key`, `ip_address`, `user_agent`, `referrer`, `timestamp`, and `is_unique`.
### Response Example
```json
{
"success": true,
"event_id": 123,
"stats": {
"total_views": 10,
"unique_views": 5
}
}
```
#### `get_stats(content_type, object_id)`
Retrieves statistics for a given content object.
- **content_type** (str) - Required - The content type of the object (e.g., 'blog.article').
- **object_id** (int) - Required - The ID of the object.
### Response Example
```json
{
"total_views": 156,
"unique_views": 89,
"first_viewed_at": "YYYY-MM-DDTHH:MM:SS",
"last_viewed_at": "YYYY-MM-DDTHH:MM:SS"
}
```
#### `check_unique_view(session_key, content_type, object_id)`
Checks if a view from a given session is unique for a specific object.
- **session_key** (str) - Required - The session identifier.
- **content_type** (str) - Required - The content type of the object.
- **object_id** (int) - Required - The ID of the object.
### Async Provider (`AsyncDatabaseProvider`)
#### `get_stats(content_type, object_id)`
Asynchronous method to retrieve statistics for a given content object.
- **content_type** (str) - Required - The content type of the object.
- **object_id** (int) - Required - The ID of the object.
### Request Example (Async)
```python
from djinsight.providers.database import AsyncDatabaseProvider
async def my_async_view(request):
async_provider = AsyncDatabaseProvider()
stats = await async_provider.get_stats('blog.article', 42)
return JsonResponse(stats)
```
```
--------------------------------
### get_site_overview
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Retrieves a site-wide analytics overview aggregating all tracked content types.
```APIDOC
## get_site_overview
### Description
Get site-wide analytics overview aggregating all tracked content types.
### Response
#### Success Response (200)
- **total_views** (integer) - Total site views.
- **total_unique_views** (integer) - Total unique site views.
- **tracked_objects** (integer) - Total number of tracked objects.
- **by_content_type** (array) - Breakdown by content type.
### Response Example
{
"total_views": 125000,
"total_unique_views": 67500,
"tracked_objects": 1250,
"by_content_type": [
{
"content_type": "blog.article",
"total_views": 85000,
"unique_views": 45000,
"object_count": 450
}
]
}
```
--------------------------------
### Customizing Renderers and Providers
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Djinsight's architecture is extensible. You can define custom renderers (e.g., `WIDGET_RENDERER`, `CHART_RENDERER`) and providers (e.g., `PROVIDER_CLASS`) in your settings.
```python
DJINSIGHT = {
'WIDGET_RENDERER': 'myapp.renderers.MyWidgetRenderer',
'PROVIDER_CLASS': 'myapp.providers.MyRedisProvider',
}
```
--------------------------------
### Using the Universal Stats Template Tag
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
The `{% stats %}` tag replaces over 20 older tags. Specify `metric`, `period`, `output`, `chart_type`, and `chart_color` for flexible data retrieval and visualization.
```django
{% stats metric="views" period="week" output="chart" chart_type="line" %}
```
```django
{% stats metric="views" period="today" %}
```
--------------------------------
### Render View Counts in Django Templates
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/djinsight/templates/djinsight/widgets/stats_badge.html
Logic for displaying total, unique, or standard view counts with fallback values.
```django
{% if data.total_views is not None %} {{ data.total_views|default:0 }} views {% elif data.unique_views is not None %} {{ data.unique_views|default:0 }} unique {% elif data.views is not None %} {% if data.views|length > 0 %} {{ data.views|length }} {% else %} {{ data.views|default:0 }} {% endif %} {% else %} 0 {% endif %}
```
--------------------------------
### Vanilla JavaScript Mini Chart Rendering
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/djinsight/wagtail/templates/djinsight/wagtail/panels/analytics_panel.html
A dependency-free canvas chart implementation that consumes JSON-serialized data from the Django context.
```javascript
(function() { var canvas = document.getElementById('djinsight-mini-chart'); if (!canvas) return; var labels = {{ chart_labels|safe }}; var data = {{ chart_data|safe }}; // Simple canvas chart — no dependencies var ctx = canvas.getContext('2d'); var w = canvas.width, h = canvas.height; var pad = {top: 10, right: 10, bottom: 30, left: 40}; var cw = w - pad.left - pad.right; var ch = h - pad.top - pad.bottom; var max = Math.max.apply(null, data) || 1; // Background ctx.fillStyle = '#f8f9fa'; ctx.fillRect(0, 0, w, h); // Grid lines ctx.strokeStyle = '#e9ecef'; ctx.lineWidth = 1; for (var g = 0; g <= 4; g++) { var gy = pad.top + ch - (ch * g / 4); ctx.beginPath(); ctx.moveTo(pad.left, gy); ctx.lineTo(w - pad.right, gy); ctx.stroke(); ctx.fillStyle = '#999'; ctx.font = '11px sans-serif'; ctx.textAlign = 'right'; ctx.fillText(Math.round(max * g / 4), pad.left - 6, gy + 4); } // Bars var barW = cw / data.length * 0.6; var gap = cw / data.length; ctx.fillStyle = '#007bff'; for (var i = 0; i < data.length; i++) { var barH = (data[i] / max) * ch; var x = pad.left + gap * i + (gap - barW) / 2; var y = pad.top + ch - barH; ctx.fillRect(x, y, barW, barH); // Labels ctx.fillStyle = '#666'; ctx.font = '11px sans-serif'; ctx.textAlign = 'center'; ctx.fillText(labels[i], pad.left + gap * i + gap / 2, h - 8); ctx.fillStyle = '#007bff'; } })();
```
--------------------------------
### Query statistics by time period with StatsQueryMixin
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Use StatsQueryMixin to easily retrieve view counts for specific time intervals, optionally including chart data.
```python
from djinsight.models import StatsQueryMixin
# Get views for today
article = Article.objects.get(pk=42)
views_today = StatsQueryMixin.get_views_today(article)
# Get views with chart data (returns list of hourly/daily data points)
chart_data = StatsQueryMixin.get_views_today(article, chart_data=True)
# Returns: [{'date': '2024-03-20 10:00', 'label': '10:00', 'count': 5}, ...]
# Different period methods
views_week = StatsQueryMixin.get_views_week(article)
views_month = StatsQueryMixin.get_views_month(article)
views_year = StatsQueryMixin.get_views_year(article)
# With chart data for visualization
week_chart = StatsQueryMixin.get_views_week(article, chart_data=True)
# Returns: [{'date': '2024-03-14', 'label': 'Thu', 'count': 25}, ...]
month_chart = StatsQueryMixin.get_views_month(article, chart_data=True)
# Returns: [{'date': '2024-02-20', 'label': '20 Feb', 'count': 45}, ...]
year_chart = StatsQueryMixin.get_views_year(article, chart_data=True)
# Returns: [{'date': '2024-03', 'label': 'Mar 2024', 'count': 1200}, ...]
```
--------------------------------
### Display Blog Posts with Djinsight Stats
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/examples/django/blog/templates/blog/post_list.html
Use this template snippet to iterate through a list of posts and display their titles, URLs, creation dates, and view counts. Ensure the 'posts' variable is available in the context. The {% stats %} tag requires the 'obj' argument to be set to the current post object.
```Django Template
{% load djinsight_tags %}
{% if posts %}
{% for post in posts %}* [{{ post.title }}]({{ post.get_absolute_url }}) ({{ post.created_at|date:"Y-m-d" }}) Views: {% stats obj=post %}
{% endfor %}
{% else %}
No posts yet. [Create one in admin](/admin/blog/post/add/).
{% endif %}
```
--------------------------------
### POST /djinsight/record-view/
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Records a page view. This endpoint is used to track when a user visits a page on your website.
```APIDOC
## POST /djinsight/record-view/
### Description
Records a page view. This endpoint is used to track when a user visits a page on your website.
### Method
POST
### Endpoint
/djinsight/record-view/
### Request Body
- **url** (string) - Required - The URL of the page being viewed.
- **content_type** (string) - Optional - The content type of the object being viewed (e.g., 'blog.article').
- **object_id** (integer) - Optional - The ID of the object being viewed.
### Request Example
{
"url": "/blog/my-first-post/",
"content_type": "blog.article",
"object_id": 123
}
### Response
#### Success Response (200)
- **message** (string) - A success message indicating the view was recorded.
#### Response Example
{
"message": "Page view recorded successfully."
}
```
--------------------------------
### Rollback djinsight Version
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Restore data and downgrade the package version to a previous release.
```bash
python manage.py loaddata djinsight_backup.json
pip install djinsight==0.1.9
python manage.py migrate djinsight
```
--------------------------------
### StatsQueryMixin Model
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Documentation for the StatsQueryMixin, providing convenient methods for querying view statistics across different time periods.
```APIDOC
## Model: StatsQueryMixin
### Description
Mixin class providing convenient methods for querying view statistics across different time periods (today, week, month, year), with options to retrieve chart data.
### Usage
#### Getting views for today
```python
from djinsight.models import StatsQueryMixin
from myapp.models import Article
article = Article.objects.get(pk=42)
views_today = StatsQueryMixin.get_views_today(article)
```
#### Getting views with chart data for today
```python
from djinsight.models import StatsQueryMixin
from myapp.models import Article
article = Article.objects.get(pk=42)
chart_data_today = StatsQueryMixin.get_views_today(article, chart_data=True)
# Returns: [{'date': '2024-03-20 10:00', 'label': '10:00', 'count': 5}, ...]
```
#### Getting views for different periods
```python
from djinsight.models import StatsQueryMixin
from myapp.models import Article
article = Article.objects.get(pk=42)
views_week = StatsQueryMixin.get_views_week(article)
views_month = StatsQueryMixin.get_views_month(article)
views_year = StatsQueryMixin.get_views_year(article)
```
#### Getting chart data for different periods
```python
from djinsight.models import StatsQueryMixin
from myapp.models import Article
article = Article.objects.get(pk=42)
# Weekly chart data
week_chart = StatsQueryMixin.get_views_week(article, chart_data=True)
# Returns: [{'date': '2024-03-14', 'label': 'Thu', 'count': 25}, ...]
# Monthly chart data
month_chart = StatsQueryMixin.get_views_month(article, chart_data=True)
# Returns: [{'date': '2024-02-20', 'label': '20 Feb', 'count': 45}, ...]
# Yearly chart data
year_chart = StatsQueryMixin.get_views_year(article, chart_data=True)
# Returns: [{'date': '2024-03', 'label': 'Mar 2024', 'count': 1200}, ...]
```
```
--------------------------------
### List Tracked Models
Source: https://context7.com/krystianmagdziarz/djinsight/llms.txt
Lists all content types currently registered for tracking in the system.
```python
from djinsight.mcp.tools.basic import list_tracked_models
result = list_tracked_models()
# Returns:
{
"tracked_models": [
{
"app_label": "blog",
"model": "article",
"content_type": "blog.article",
"track_anonymous": True,
"track_authenticated": True
},
{
"app_label": "products",
"model": "product",
"content_type": "products.product",
"track_anonymous": True,
"track_authenticated": True
},
{
"app_label": "wagtailcore",
"model": "page",
"content_type": "wagtailcore.page",
"track_anonymous": True,
"track_authenticated": False
}
]
}
```
--------------------------------
### Code Quality Checks
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CONTRIBUTING.md
Perform code quality checks using Black for formatting, isort for import sorting, flake8 for linting, and mypy for type checking. These commands ensure code consistency and quality.
```bash
# Format code with Black
black djinsight/
# Sort imports with isort
isort djinsight/
# Lint with flake8
flake8 djinsight/
# Type checking with mypy
mypy djinsight/
# Run all quality checks
black djinsight/ && isort djinsight/ && flake8 djinsight/ && mypy djinsight/
```
--------------------------------
### Registering Tracked Models with ContentTypeRegistry
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Use `ContentTypeRegistry.register()` to explicitly register models that Djinsight should track. This replaces the need for mixins.
```python
ContentTypeRegistry.register(YourModel)
```
--------------------------------
### Update Django Templates
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/MIGRATION_GUIDE.md
Replace legacy tracking and statistics tags with the universal {% track %} and {% stats %} tags.
```django
{% load djinsight_tags %}
{# Replace {% page_view_tracker %} with: #}
{% track %}
{# Replace individual stat tags: #}
{% stats metric="views" period="week" output="chart" chart_type="line" chart_color="#007bff" %}
```
--------------------------------
### Configuring Automatic Middleware Tracking
Source: https://github.com/krystianmagdziarz/djinsight/blob/main/CHANGELOG.md
Enable automatic injection of tracking scripts by setting `DJINSIGHT['AUTO_INJECT_TRACKING']` to `True` in your Django settings.
```python
DJINSIGHT = {
'AUTO_INJECT_TRACKING': True,
}
```