django-htmx-fun A small Django application to advertise the fun htmx can bring you

django-htmx-fun

A small Django application to advertise the fun htmx can bring you.

It implements a Single-Page-Application for writing a diary.

The entries in the diary database get lazy loaded (endless scrolling) via hx-trigger=”revealed”

Why I love htmx ?

If you look into the past then one thing is clear: stateless has won. Nobody starts a new project with Corba these days. Stateless http is the winner .

I don’t understand why JavaScript based frontend frameworks seem to be the only way for new projects.

I want the client/browser to be SSS (simple, stupid and stateless) .

I need to validate my data on the server anyway. So why should I validate them on the client?

The Django Forms library has all you need to write database focused applications.

Sending HTML fragements over the wire keeps my application simple.

There is just one thing which is outdated (although it is still perfectly fine). The need for a full page refresh after submitting a form.

I want html pages with several small forms and I want to load and submit each of them individually. This does not mean I want to write a Single-Page-Application. There are more colors than black and white.

For more about htmx see the homepage: htmx.org

HTMX: Frontend Revolution (Slides from DjangoCon EU 2021)

Naming Pattern

Here is my personal naming pattern, which helps me to read the source more easily


_page()

foo_page(request, …).

Function based view. Returns a HttpResponse with a full page.

URL

/foo


_hx()

foo_hx(request, …)

Function based view. This method should be called via HTTP-GET. Returns a HttpResponse which only contains a HTML fragment.

URL

/foo_hx


_hxpost()

foo_hxpost(request, …)

Function based view. This methods should be called via HTTP-POST. Returns a HttpResponse which only contains a HTML fragment.

URL

/foo_hxpost


_html():

Python method which returns a HTML SafeString.

Usually created via format_html()

Flat URL Namespace

Above naming pattern makes it very use to get to the corresponding code.

Imagine you get a message from tool monitoring your servers.

There is an exception at URL “/sunshine/123”, then I know the name of the method which handles this URL. The method is “sunshine_page()”.

If you need several pages for a model, then you will not use “/sunshine/foo” and “/sunshine/bar”, but instead “/sunshine_foo” and “/sunshine_bar”.

Opinionated Best Practices

I like it conditionless. I try to avoid to have too many “if” and “else”.

I avoid to use if request.method == ‘POST’.

I don’t use the special http headers which get added by htmx. I avoid this (pseudo code): “if request is a htmx request, then …”.

Instead I create two endpoints: One which returns a full page, one which returns a fragment.

Pull Requests are welcome

You have an idea how to improve this example ? Great! Just do it, provide a pull request and I will merge it.