Home Backend Development Python Tutorial Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

Jan 06, 2025 am 12:00 AM

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:

Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding 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
]
Copy after login

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"),
]
Copy after login

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)

Copy after login

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
Copy after login

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
]
Copy after login

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 %}

Copy after login

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
]
Copy after login

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})

Copy after login

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:

Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

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

Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

Response

Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles