Skip to main content

Django Admin AI Search

PyPI version Python versions Django versions CI codecov License: MIT

AI-powered natural language search for Django Admin. Ask questions like "Find all users created today" or "Show orders over $1000" and get instant results.

Installation

pip install django-admin-ai-search

Quick Start

1. Add to INSTALLED_APPS

Add django_admin_ai_search before django.contrib.admin:

INSTALLED_APPS = [
    "django_admin_ai_search",  # Must be before django.contrib.admin
    "django.contrib.admin",
    # ...
]

2. Add URL patterns

from django.urls import include, path
from django_admin_ai_search.urls import get_urlpatterns as get_ai_search_urls

urlpatterns = [
    path("admin/ai-search/", include("django_admin_ai_search.urls")),
    path("admin/", admin.site.urls),
    # ...
]

# Add search page URLs
urlpatterns += get_ai_search_urls()

3. Configure your LLM generator

Create a generator class that implements the QueryGenerator protocol:

# myapp/generators.py
import json
from openai import OpenAI
from django_admin_ai_search import QueryGenerator, get_system_prompt

class OpenAIGenerator(QueryGenerator):
    def __init__(self):
        self.client = OpenAI()  # Uses OPENAI_API_KEY env var

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        response = self.client.chat.completions.create(
            model="gpt-5.2",
            messages=[
                {"role": "system", "content": get_system_prompt(model_schema)},
                {"role": "user", "content": user_query},
            ]
        )
        return json.loads(response.choices[0].message.content)

4. Add settings

DJANGO_ADMIN_AI_SEARCH = {
    "GENERATOR": "myapp.generators.OpenAIGenerator",
    "CACHE_TIMEOUT": 3600,  # Cache results for 1 hour (optional)
    "CACHE_PREFIX": "ai_search",  # Cache key prefix (optional)
}

Generator Examples

OpenAI
import json
from openai import OpenAI
from django_admin_ai_search import QueryGenerator, get_system_prompt

class OpenAIGenerator(QueryGenerator):
    def __init__(self, model: str = "gpt-5.2"):
        self.client = OpenAI()
        self.model = model

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": get_system_prompt(model_schema)},
                {"role": "user", "content": user_query},
            ]
        )
        return json.loads(response.choices[0].message.content)
Anthropic
import json
from anthropic import Anthropic
from django_admin_ai_search import QueryGenerator, get_system_prompt

class AnthropicGenerator(QueryGenerator):
    def __init__(self, model: str = "claude-opus-4-5-20251101"):
        self.client = Anthropic()
        self.model = model

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        response = self.client.messages.create(
            model=self.model,
            max_tokens=1024,
            system=get_system_prompt(model_schema),
            messages=[{"role": "user", "content": user_query}]
        )
        return json.loads(response.content[0].text)
AWS Bedrock
import json
import boto3
from django_admin_ai_search import QueryGenerator, get_system_prompt

class BedrockGenerator(QueryGenerator):
    def __init__(self, model_id: str = "anthropic.claude-opus-4-5-20251101-v1:0"):
        self.client = boto3.client("bedrock-runtime")
        self.model_id = model_id

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        response = self.client.converse(
            modelId=self.model_id,
            system=[{"text": get_system_prompt(model_schema)}],
            messages=[{"role": "user", "content": [{"text": user_query}]}]
        )
        return json.loads(response["output"]["message"]["content"][0]["text"])
LangChain
import json
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from django_admin_ai_search import QueryGenerator, get_system_prompt

class LangChainGenerator(QueryGenerator):
    def __init__(self):
        self.llm = ChatOpenAI(model="gpt-5.2", temperature=0)

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        prompt = ChatPromptTemplate.from_messages([
            ("system", get_system_prompt(model_schema)),
            ("human", "{query}"),
        ])
        chain = prompt | self.llm
        response = chain.invoke({"query": user_query})
        return json.loads(response.content)
Pydantic-AI
from pydantic import BaseModel
from pydantic_ai import Agent
from django_admin_ai_search import QueryGenerator, get_system_prompt

class QueryResult(BaseModel):
    code: str
    explanation: str
    app_label: str
    model_name: str

class PydanticAIGenerator(QueryGenerator):
    def __init__(self):
        self.agent = Agent("openai:gpt-5.2", result_type=QueryResult)

    def generate(self, user_query: str, model_schema: list[dict]) -> dict:
        result = self.agent.run_sync(
            user_query,
            system_prompt=get_system_prompt(model_schema)
        )
        return result.data.model_dump()

Configuration Options

DJANGO_ADMIN_AI_SEARCH = {
    # Required: Your generator class or instance
    "GENERATOR": "myapp.generators.OpenAIGenerator",

    # Optional: Cache timeout in seconds (default: 3600)
    "CACHE_TIMEOUT": 3600,

    # Optional: Cache key prefix (default: "django_admin_ai_search")
    "CACHE_PREFIX": "django_admin_ai_search",
}

How It Works

  1. User enters a natural language query in the Django admin search box
  2. The package extracts schema information from all registered admin models
  3. Your generator receives the query and schema, calls your LLM, and returns structured JSON
  4. The package executes the generated Django ORM code safely
  5. Results are displayed in a dynamic table with clickable links to admin change pages

Security

  • Only read-only queries are allowed (no UPDATE, DELETE, CREATE, etc.)
  • Queries are limited to 50 results
  • Only models registered in Django admin are queryable
  • Staff authentication required for all endpoints

Development

# Clone the repository
git clone https://github.com/quanhea/django-admin-ai-search.git
cd django-admin-ai-search

# Install dependencies
uv sync

# Install pre-commit hooks
uv run pre-commit install --hook-type pre-commit --hook-type pre-push

# Run tests
uv run pytest

# Build package
uv build

Demo / UI Preview

Run the demo Django project to preview the UI:

uv run python demo/manage.py migrate
uv run python demo/manage.py createsuperuser
uv run python demo/manage.py runserver

Then visit http://localhost:8000/admin/ and log in (demo credentials: admin/admin). The demo uses a mock generator so you can test the UI without an actual LLM.

License

MIT

Metadata

Release files for django-admin-ai-search 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-admin-ai-search 0.1.1
File Size Uploaded Provenance Actions
django_admin_ai_search-0.1.1.tar.gz 16.8 kB With provenance Details for django_admin_ai_search-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-admin-ai-search 0.1.1
File Interpreter ABI Platform Actions
django_admin_ai_search-0.1.1-py3-none-any.whl Python 3 none any Details for django_admin_ai_search-0.1.1-py3-none-any.whl

Total release size: 32.2 kB

Release files / django_admin_ai_search-0.1.1.tar.gz

Download URL django_admin_ai_search-0.1.1.tar.gz
Size 16.8 kB
Tags Source
SHA-256 checksum
How to use checksums
074361b8bb20d26908e9ca4f2f7ec155702937f8b1203919c4482f4335166ffe
BLAKE2b-256 checksum
How to use checksums
48013c7afa2283fb4cbe387bbad959d279a8d3111a43bcc9223548ba0c091a09
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 18, 2025.

Transparency log

Release files / django_admin_ai_search-0.1.1-py3-none-any.whl

Download URL django_admin_ai_search-0.1.1-py3-none-any.whl
Size 15.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a1788867b0079edfb35536666f286222ddf206edd8ef8f57200f004a81dd0d2d
BLAKE2b-256 checksum
How to use checksums
1c5f47088cc6b0df09df1e56f67e374407093ff1778761514ad62660ea7b85cf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 18, 2025.

Transparency log

Security for django-admin-ai-search 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_admin_ai_search-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 18, 2025.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page