Skip to main content
DjangoKit Log In

Handlers

Handlers are simplified Django endpoints that can return any kind of response, although they typically return data that can be JSONified. Handlers are often coupled with pages, but you can also create standalone handlers that can act as API endpoints, render templates, etc (just like a normal Django view).

The idea behind handlers is that you often want to return data that's converted to JSON, and you also want to be able to easily handle errors and return appropriate responses.

Handlers are very similar to Django views with the major difference being that you can return any of the following:

  • a model instance
  • a dict that contains a model instance or instances
  • a dict that contains arbitrary data (so long as it can be JSONified)
  • an HTTP status code and some data (model instance or dict)
  • just an HTTP status code
  • an HTTP redirect status code and a string containing the redirect location
  • an HTTP status code and a string containing a message (typically used for error responses)
  • a Django response object when you need complete control over the response

Adding a Handler

To add a new handler to a DjangoKit project, you simply add a handlers.py module (along with an adjacent __init__.py) somewhere in your project's routes directory (see Code Layout).

Using the DjangoKit CLI, you can add a handler like so:

dk add-handler <route_path>

<route_path> should be relative to your project's routes directory, so if you wanted to create a handler for the todo route, you'd run dk add-handler todo and you'd end up with a new subdirectory under routes:

<project>/src/<package>/routes/
    todo/
        __init__.py
        handlers.py

These handlers will be accessible at the URL /todo.

handlers.py will contain a stub get handler that you can fill in. You can also add handlers for delete, head, options, patch, post, and put.

Subpath Handlers

You can also add arbitrary handler functions that will be loaded at a subpath of the route:

# <package>/routes/todo/handlers.py
from djangokit.core import handler

from <package>.models import TodoItem


def get(_request):
    """Get all todo items (path = /todo)."""
    items = TodoItem.objects.all().order_by("created")
    return {
        "todo": [item for item in items if not item.completed],
        "completed": [item for item in items if item.completed],
    }


@handler("get")
def completed(_request):
    """Get completed todo items (path = /todo/completed)."""
    items = TodoItem.objects.filter(completed=True).order_by("created")
    return {"items": items}