


Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX
Jan 06, 2025 am 12:00 AMWelcome to part 3 of our series! In this series of articles, I am documenting my own learning of HTMX, using Django for the backend.
If you just arrived in the series you may want to check parts one and two first.
Creating the templates and views
We will start by creating a base template, and an index template that points to an index view, that will list the Todos we have in the database. We will use DaisyUI which is an extension of Tailwind CSS, to make the Todos decent-looking.
This is how the page to look like once the views are set, and before we add HTMX:
Adding the views and URLs
First we need to update the urls.py file in the root of the project, to include the urls that we will define in our "core" app:
# todomx/urls.py from django.contrib import admin from django.urls import include, path # <-- NEW urlpatterns = [ path("admin/", admin.site.urls), path("", include("core.urls")), # <-- NEW ]
Then, we define the new URLs for the app, placing adding new file core/urls.py:
# core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("tasks/", views.tasks, name="tasks"), ]
Now we can create the corresponding views, in core/views.py
# core/views.py from django.shortcuts import redirect, render from .models import UserProfile, Todo from django.contrib.auth.decorators import login_required def index(request): return redirect("tasks/") def get_user_todos(user: UserProfile) -> list[Todo]: return user.todos.all().order_by("created_at") @login_required def tasks(request): context = { "todos": get_user_todos(request.user), "fullname": request.user.get_full_name() or request.user.username, } return render(request, "tasks.html", context)
A few interesting things here: our index route (home page) will just redirect to the tasks URL and view. This will give us the freedom to implement some sort of landing page for the app in the future.
The tasks view requires login, and returns two attributes in the context: the user's fullname, which coalesce to their username if needed, and the todo items, sorted by creation date (we can add some sorting options for the user in the future).
Now let's add the templates. We'll have a base template for the whole app, which will include Tailwind CSS and DaisyUI, and the template for the tasks view.
<!-- core/templates/_base.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link href="https://cdn.jsdelivr.net/npm/daisyui@5.0.0-beta.1/daisyui.css" rel="stylesheet" type="text/css"/> <script src="https://cdn.tailwindcss.com?plugins=typography"></script> {% block header %} {% endblock %} </head> <body> <p>Note that we're adding Tailwind and DaisyUI from a CDN, to keep these articles simpler. For production-quality code, they should be bundled in your app.</p> <p>We're using the beta version of DaisyUI 5.0, which includes a new list component which suits our todo items fine.<br> </p> <pre class="brush:php;toolbar:false"><!-- core/templates/tasks.html --> {% extends "_base.html" %} {% block content %} <div> <p>We can now add some Todo items with the admin interface, and run the server, to see the Todos similarly to the previous screenshot. </p> <p>We're now ready to add some HTMX to the app, to toggle the completion of the item</p> <h2> Add inline partial templates </h2> <p>In case you're new to HTMX, it's a JavaScript library that makes it easy to create dynamic web pages by replacing and updating parts of the page with fresh content from the server. Unlike client-side libraries like React, HTMX focuses on <strong>server-driven</strong> updates, leveraging <strong>hypermedia</strong> (HTML) to fetch and manipulate page content on the server, which is responsible for rendering the updated content, rather than relying on complex client-side rendering and rehydration, and saving us from the toil of serializing to and from JSON just to provide data to client-side libraries.</p> <p>In short: when we toggle one of our todo items, we will get a new fragment of HTML from the server (the todo item) with its new state.</p> <p>To help us achieve this we will first install a Django plugin called django-template-partials, which adds support to inline partials in our template, the same partials that we will later return for specific todo items.<br> </p> <pre class="brush:php;toolbar:false">? uv add django-template-partials Resolved 24 packages in 435ms Installed 1 package in 10ms + django-template-partials==24.4
Following the installation instructions, we should update our settings.py file as such
INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "core", "template_partials", # <-- NEW ]
In our tasks template, we will define each todo item as an inline partial template. If we reload the page, it shouldn't have any visual differences.
<!-- core/templates/tasks.html --> {% extends "_base.html" %} {% load partials %} <!-- NEW --> {% block content %} <div> <p>The two attributes added are important: the name of the partial, todo-item-partial, will be used to refer to it in our view and other templates, and the inline attribute indicates that we want to keep rendering the partial within the context of its parent template.</p> <p>With inline partials, you can see the template within the context it lives in, making it easier to understand and maintain your codebase by preserving locality of behavior, when compared to including separate template files.</p> <h2> Toggling todo items on and off with HTMX </h2> <p>To mark items as complete and incomplete, we will implement a new URL and View for todo items, using the PUT method. The view will return the updated todo item rendered within a partial template.</p> <p>First of all we need to add HTMX to our base template. Again, we're adding straight from a CDN for the sake of simplicity, but for real production apps you should serve them from the application itself, or as part of a bundle. Let's add it in the HEAD section of _base.html, right after Tailwind:<br> </p> <pre class="brush:php;toolbar:false"> <link href="https://cdn.jsdelivr.net/npm/daisyui@5.0.0-beta.1/daisyui.css" rel="stylesheet" type="text/css"/> <script src="https://cdn.tailwindcss.com?plugins=typography"></script> <script src="https://unpkg.com/htmx.org@2.0.4" ></script> <!-- NEW --> {% block header %} {% endblock %}
On core/urls.py we will add our new route:
# core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("tasks/", views.tasks, name="tasks"), path("tasks/<int:task_id>/", views.toggle_todo, name="toggle_todo"), # <-- NEW ]
Then, on core/views.py, we will add the corresponding view:
# core/views.py from django.shortcuts import redirect, render from .models import UserProfile, Todo from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods # <-- NEW # ... existing code # NEW @login_required @require_http_methods(["PUT"]) def toggle_todo(request, task_id): todo = request.user.todos.get(id=task_id) todo.is_completed = not todo.is_completed todo.save() return render(request, "tasks.html#todo-item-partial", {"todo": todo})
In the return statement, we can see how we can leverage template partials: we're returning only the partial, by referring to its name todo-item-partial, and the context that matches the name of the item we're iterating in the loop in tasks.html.
We can now test toggling the item on and off:
It looks like we're just doing some client-side work, but inspecting the Network tool in the browser shows us how we're dispatching PUT requests and returning the partial HTML:
PUT request
Response
Our app is now HTMX-fied! You can check the final code here. In part 4, we will add the ability to add and delete tasks.
The above is the detailed content of Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Web application security needs to be paid attention to. Common vulnerabilities on Python websites include XSS, SQL injection, CSRF and file upload risks. For XSS, the template engine should be used to automatically escape, filter rich text HTML and set CSP policies; to prevent SQL injection, parameterized query or ORM framework, and verify user input; to prevent CSRF, CSRFTToken mechanism must be enabled and sensitive operations must be confirmed twice; file upload vulnerabilities must be used to restrict types, rename files, and prohibit execution permissions. Following the norms and using mature tools can effectively reduce risks, and safety needs continuous attention and testing.

Python's unittest and pytest are two widely used testing frameworks that simplify the writing, organizing and running of automated tests. 1. Both support automatic discovery of test cases and provide a clear test structure: unittest defines tests by inheriting the TestCase class and starting with test\_; pytest is more concise, just need a function starting with test\_. 2. They all have built-in assertion support: unittest provides assertEqual, assertTrue and other methods, while pytest uses an enhanced assert statement to automatically display the failure details. 3. All have mechanisms for handling test preparation and cleaning: un

Python's default parameters are only initialized once when defined. If mutable objects (such as lists or dictionaries) are used as default parameters, unexpected behavior may be caused. For example, when using an empty list as the default parameter, multiple calls to the function will reuse the same list instead of generating a new list each time. Problems caused by this behavior include: 1. Unexpected sharing of data between function calls; 2. The results of subsequent calls are affected by previous calls, increasing the difficulty of debugging; 3. It causes logical errors and is difficult to detect; 4. It is easy to confuse both novice and experienced developers. To avoid problems, the best practice is to set the default value to None and create a new object inside the function, such as using my_list=None instead of my_list=[] and initially in the function

Deploying Python applications to production environments requires attention to stability, security and maintenance. First, use Gunicorn or uWSGI to replace the development server to support concurrent processing; second, cooperate with Nginx as a reverse proxy to improve performance; third, configure the number of processes according to the number of CPU cores to optimize resources; fourth, use a virtual environment to isolate dependencies and freeze versions to ensure consistency; fifth, enable detailed logs, integrate monitoring systems, and set up alarm mechanisms to facilitate operation and maintenance; sixth, avoid root permissions to run applications, close debugging information, and configure HTTPS to ensure security; finally, automatic deployment is achieved through CI/CD tools to reduce human errors.

Python works well with other languages ??and systems in microservice architecture, the key is how each service runs independently and communicates effectively. 1. Using standard APIs and communication protocols (such as HTTP, REST, gRPC), Python builds APIs through frameworks such as Flask and FastAPI, and uses requests or httpx to call other language services; 2. Using message brokers (such as Kafka, RabbitMQ, Redis) to realize asynchronous communication, Python services can publish messages for other language consumers to process, improving system decoupling, scalability and fault tolerance; 3. Expand or embed other language runtimes (such as Jython) through C/C to achieve implementation

PythonisidealfordataanalysisduetoNumPyandPandas.1)NumPyexcelsatnumericalcomputationswithfast,multi-dimensionalarraysandvectorizedoperationslikenp.sqrt().2)PandashandlesstructureddatawithSeriesandDataFrames,supportingtaskslikeloading,cleaning,filterin

To implement a custom iterator, you need to define the __iter__ and __next__ methods in the class. ① The __iter__ method returns the iterator object itself, usually self, to be compatible with iterative environments such as for loops; ② The __next__ method controls the value of each iteration, returns the next element in the sequence, and when there are no more items, StopIteration exception should be thrown; ③ The status must be tracked correctly and the termination conditions must be set to avoid infinite loops; ④ Complex logic such as file line filtering, and pay attention to resource cleaning and memory management; ⑤ For simple logic, you can consider using the generator function yield instead, but you need to choose a suitable method based on the specific scenario.

Python's list, dictionary and collection derivation improves code readability and writing efficiency through concise syntax. They are suitable for simplifying iteration and conversion operations, such as replacing multi-line loops with single-line code to implement element transformation or filtering. 1. List comprehensions such as [x2forxinrange(10)] can directly generate square sequences; 2. Dictionary comprehensions such as {x:x2forxinrange(5)} clearly express key-value mapping; 3. Conditional filtering such as [xforxinnumbersifx%2==0] makes the filtering logic more intuitive; 4. Complex conditions can also be embedded, such as combining multi-condition filtering or ternary expressions; but excessive nesting or side-effect operations should be avoided to avoid reducing maintainability. The rational use of derivation can reduce
