Dec. 10, 2024

Understanding space and time travel with Django

One issue that fairly often trips up beginners with Django is understanding the relationship and timing of template rendering and Javascript execution. This confusion is often compounded by the nature of a typical local development setup, where the server (runserver) and the client (a browser) are on the same machine.

Typically the question goes along the lines of trying to manipulate some data from the view with Javascript directly or somehting similar. So let's clarify a few things here.

First there are two locations to consider with a Django project, the server and the client. The server is where Django templates are rendered and sent to the client (a browser) where the Javascript is executed. This last sentence should also reveal that the timing of when different bits of code are executed. The template is rendered first, then the Javascript, therefore it is impossible for any Javascript to have an effect on the template render process.

What is possible is to make an other request to the server once the client has loaded the initial page. This is known an "Asynchronous JavaScript And XML" (AJAX) request, with a many JS libraries making this kind of thing much easier such as HTMX, axios or the plain fetch API. Alternatively there are some Django packages that help with this such as Django-unicorn that provide an abstraction around this behaviour.

Hopefully, this will mean those beginners won't be trying to do time travel to make their applications work!