How Do HxRequests Work?

Instead of routing HTMX requests to a Django view like a normal request, hx_requests intercepts them and sends them to a dedicated HxRequest class.

How It Works

When using the hx_get and hx_post template tags:

  1. The URL of the request is set to the current page’s URL.

  2. A single hx GET parameter is added to the request URL. It carries the HxRequest name (along with the serialized object and kwargs).

  3. When the request reaches the view, HtmxViewMixin reads the name from the hx parameter and routes the request to the HxRequest with the matching name.

  4. The HxRequest processes the request and returns an Html response.

Note

The hx parameter is a signed token, not loose query params — see Object Serialization for what it packs and Why HxRequest Security Is Needed for why it is signed.

Why Not Just Use A URL Router?

At first glance, this might seem like something a URL router should handle. But using a view mixin instead has a couple of key advantages:

Access to View Context

Since the request first reaches the view, the HxRequest has access to everything the view provides. This is especially useful because you don’t have to duplicate context logic in the HxRequest.

In many cases, the HTML snippet being swapped in depends on context from the view—particularly with Django class-based views like ListView. Using a mixin ensures that context is automatically available without extra work.

Permissions Work Automatically

Because HxRequests run through the view, any permissions applied to the view also apply to the HxRequest by default. If a user can’t access the view, they also can’t access the HxRequest, eliminating the need to duplicate permission logic.

Of course, there may be cases where this isn’t the behavior you want. If needed, you can override permissions inside the HxRequest itself.

Warning

This depends on mixin ordering. On the HxRequest handoff, HtmxViewMixin.dispatch does not call super().dispatch(), so a dispatch-based auth mixin (LoginRequiredMixin, PermissionRequiredMixin) only gates the HxRequest when it is placed before HtmxViewMixin in the class’s MRO. hx_requests raises a startup system check (W001) when an auth mixin is ordered after HtmxViewMixin. For robust control, authorize on the HxRequest itself.

Warning

If an HxRequest is used across multiple views, it’s permissions depend on the view handling the request.