Skip to main content
This guide shows how to run a Upsonic agent inside a Django project. Choose Django when you need database models, user management, or admin UI alongside your agent API.

Prerequisites

  • Django 4.1+ (for async view support if you use agent.do_async())
  • A Django project already created, or follow the steps below to create one

Setup

1

Initialize the project with uv

2

Create a Django project and app

3

Register the app

Add "agent_api" to INSTALLED_APPS in myproject/settings.py.
4

Configure URLs

In myproject/urls.py, include the app URLs:
myproject/urls.py
5

Create the agent view and URL

In agent_api/views.py:
agent_api/views.py
In agent_api/urls.py (create the file):
agent_api/urls.py
6

Run the server

Call the agent: http://localhost:8000/api/ask/?query=Hello

Step 2: Docker

1

Create a `.dockerignore` file

.dockerignore
2

Create a `Dockerfile`

Dockerfile
3

Build and run the image

4

Access the app

Call the agent: http://localhost:8000/api/ask/?query=Hello
For production, replace manage.py runserver with Gunicorn:
Add Gunicorn as a dependency: uv add gunicorn.

Async view with agent.do_async()

Django 4.1+ supports async views. Use agent.do_async() so the worker is not blocked during LLM calls.
agent_api/views.py
Register the async route in agent_api/urls.py:
When using async views, run Django with an ASGI server (e.g. uvicorn or daphne). With runserver, Django runs in a single thread and async may not scale. For production use:

Using with Django auth and DB

You can use the request user and DB in the same view before or after calling the agent.
agent_api/views.py
Store agent runs in the DB by defining a model (e.g. in agent_api/models.py), running migrations, and saving after agent.do() or agent.do_async().

Key takeaways

  • Use sync views with agent.do(task) when you rely on runserver or a WSGI server.
  • Use async views with await agent.do_async(task) and an ASGI server for better concurrency.
  • Combine with Django auth, ORM, and admin when you need user management and persistence.
For a minimal API-only deployment with maximum async performance, see Deploy via FastAPI.