


Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX
Welcome 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 # <p>Then, we define the new URLs for the app, placing adding new file core/urls.py:<br> </p> <pre class="brush:php;toolbar:false"># 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 --> <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 %} <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", # <p>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.<br> </p> <pre class="brush:php;toolbar:false"><!-- 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/<task_id>/", views.toggle_todo, name="toggle_todo"), # <p>Then, on core/views.py, we will add the corresponding view:<br> </p> <pre class="brush:php;toolbar:false"># 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 # <p>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.</p> <p>We can now test toggling the item on and off:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284449958.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>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:</p><p>PUT request </p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284544580.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>Response</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284614077.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>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.</p>
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!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
