Skip to content
Tools & Demos

Building an AI-Powered Analytics Dashboard with Django

Ruslan Danelian 7 min read
Copied!
Building an AI-Powered Analytics Dashboard with Django

Traditional dashboards answer the questions someone thought of in advance. The moment a manager asks something new, such as "which campaigns got worse last month and why?", they open a ticket and wait. An AI-powered dashboard changes that: users type a question in plain English, the system translates it into a safe database query, returns a chart and a table, and highlights anything unusual without being asked. This tutorial walks through the architecture, the natural language query pipeline, prompt engineering for SQL generation, widget types, and the safeguards that keep it from becoming a liability.

It extends the techniques in our guide to real-time dashboards with Django Channels and HTMX, adding an AI layer on top of the same foundation.

Key Takeaways
  • Architecture
  • The natural language query pipeline
  • Dashboard widget types
  • Production considerations

Architecture

  • Django backend: models, a read-only reporting database role, and JSON endpoints for chart data.
  • Chart.js frontend: renders bar, line, and doughnut charts from JSON, with no build step required.
  • LLM integration: an API call (Claude, GPT, or similar) that converts questions to structured queries and writes insight summaries.
  • HTMX: swaps widgets in place when the user asks a question or filters data, without a heavy single-page app.
  • Background tasks: a scheduler that runs anomaly checks and generates insight cards.

The data source can be your own Django models, a warehouse, or an API. For marketing data, for instance, you might sync campaign metrics into PostgreSQL using the patterns in our post about querying Google Ads data with GAQL, then let the AI query that local copy.

Features

📊 Illustration: infographic summarizing Features
Visual guide: Features
  1. Ask a question. "Show me top campaigns last month by conversions" returns a chart, a table, and a one-sentence summary.
  2. Insight cards. A nightly job generates cards like "Cost per lead rose 18% week over week, driven by the Brand campaign."
  3. Anomaly alerts. Statistical checks flag unusual spikes or drops and send a notification with a short explanation.
  4. Drill down. Click a bar to ask the follow-up automatically.

It extends the techniques in our guide to real-time dashboards with Django Channels and HTMX, adding an AI layer on top of the same foundation.

The natural language query pipeline

The most important design decision: do not let the model write arbitrary SQL against your production database. Use a pipeline with several guard layers.

  1. Schema context. Build a compact description of allowed tables and columns, with plain-English descriptions and example values. This is the model's map.
  2. Generate. Ask the model to return a JSON object containing the SQL, a chart type, and a title. Prefer a restricted query spec, such as metric, dimensions, filters, and date range, if your use cases allow it. A spec is safer than raw SQL.
  3. Validate. Parse the SQL with a library such as sqlglot. Allow only SELECT statements, only whitelisted tables, no functions that write or read files, and always append a row limit.
  4. Execute safely. Run it under a read-only PostgreSQL role with a statement timeout of a few seconds and row-level restrictions for tenant data.
  5. Render. Choose the chart type from the result shape and send JSON to the frontend.
  6. Explain. Pass a small sample of the result to the model for a short summary, never the full dataset.
Pro Tip

When working on the natural language query pipeline, pick one measurable goal first, track it weekly, and only scale what the data shows is working.

Prompt engineering for SQL generation

You are a data analyst. Convert the user's question to one PostgreSQL SELECT.

Rules:
- Use only the tables and columns in the schema below.
- Never use INSERT, UPDATE, DELETE, DROP, or functions that access files.
- Always include a LIMIT of 500 or less.
- For time questions, use date_trunc and the column "date".
- If the question cannot be answered with this schema, return {"error": "..."}.

Schema:
campaigns(id, name, status)
daily_metrics(campaign_id, date, cost, clicks, conversions)

Return JSON: {"sql": "...", "chart": "bar|line|doughnut|table", "title": "..."}

Effective techniques: include two or three example question and SQL pairs for your most common patterns, describe business definitions explicitly ("cost per lead means cost divided by conversions"), and give the model permission to refuse. Log every question, query, and result status to improve prompts over time.

Want expert help with this? Let's make it happen.

Get a Free Consultation

Dashboard widget types

🎯 Illustration: diagram illustrating Dashboard widget types
Visual guide: Dashboard widget types
WidgetBest forChart.js typeData shape
KPI tileSingle headline number with changeNone (HTML)One row, one value, comparison value
Trend lineMetrics over timelineDate and value series
Ranked barsTop N comparisonsbar (horizontal)Category and value
CompositionShare of totaldoughnutFew categories and values
Data tableDetail and exportNone (HTML)Many columns
Insight cardAI-written highlights and alertsNone (HTML)Text, severity, link to query

Code architecture overview

⚙️ Illustration: architecture diagram illustrating Code architecture overview
Visual guide: Code architecture overview
  • analytics/schema.py builds the schema description from an allowlist.
  • analytics/nl2sql.py calls the model, validates output, and returns a structured query object.
  • analytics/executor.py runs queries under the read-only connection with timeouts.
  • analytics/insights.py contains scheduled jobs for insight cards and anomaly detection, using z-scores or seasonal baselines.
  • analytics/views.py exposes an HTMX endpoint for questions and JSON endpoints for charts.

Add a second database alias in Django settings for the read-only role, and route reporting queries to it with a simple database router.

Production considerations

  • Cost control: cache identical questions, use a smaller model for classification, and cap tokens per request.
  • Trust: always show the generated SQL or query spec so analysts can verify it.
  • Privacy: send the model schema and small samples only, not raw customer records.
  • Accuracy: test with a fixed suite of questions and expected answers every time you change a prompt.

Dashboards like this are one of the highest-return uses of AI inside a business, as discussed in automating business workflows with AI. If you want one built around your own data, see our AI tools and dashboards service.

Related reading: Real-Time Dashboards with Django Channels and HTMX | GAQL: Querying Google Ads Data as a Developer | Automating Business Workflows with AI: High-ROI Targets

Want a dashboard your team can simply ask questions? Explore my AI tools and dashboards service or get in touch for a free consultation.

Building an AI-Powered Analytics Dashboard with Django infographic (English version)
Building an AI-Powered Analytics Dashboard with Django infographic (versión en español)
Building an AI-Powered Analytics Dashboard with Django infographic (версия на русском)
📌 Save this infographic for quick reference

Frequently Asked Questions

Is it safe to let an LLM write SQL for my database?

It is safe only with strong guardrails: a read-only database role, query validation that allows only SELECT on whitelisted tables, statement timeouts, row limits, and logging. A restricted query specification is even safer than raw SQL.

Which LLM is best for natural language to SQL?

Current top models from Anthropic, OpenAI, and Google all perform well when given a clear schema and examples. Test several on your own question set, since schema complexity matters more than the vendor.

Do I need a data warehouse for an AI analytics dashboard?

Not for small and mid-sized data. A well-indexed PostgreSQL database, possibly a read replica, is enough. Move to a warehouse when query volume or data size outgrows it.

Ruslan Danelian
Ruslan Danelian

Full-stack developer specializing in Django, AI automation, and Google Ads management. Building production SaaS platforms and custom web applications for businesses across the US.

Read next

Tools & Demos

GAQL: Querying Google Ads Data Like a Developer

Google Ads Query Language lets you pull campaign data with SQL-like precision. Here are the queries every developer and ads manager should know, from basic reporting to advanced segmentation.

10 min read

Have a project in mind?

Tell me what you need. I'll send you a plan with timeline and fixed price within one business day.

Year-end offer

20% off AI tools & custom CRM

AI chat assistants, DM bots, lead scoring and a CRM built around your business.

Claim 20% off