使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是文章学习者,那么本文《使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
This is part two of our series on building a todo application with htmx and Django. Click here to view Part 1.
In Part 2, we'll create the todo model and implement its basic functionality via unit testing.
Creating the Todo Model
In models.py, we create the todo model and its basic attributes. We want to associate todo items with a userprofile so that users can only see their own items. A todo item will also have a title and a boolean attribute is_completed. We have many future ideas for the todo model, such as the ability to set tasks to "in progress" in addition to completed or not started, and deadlines, but that's for later. For now, let's keep it simple and get something on the screen as quickly as possible.
Note: In a real-world application, we should probably consider using uuids as primary keys for both the userprofile and todo models, but we'll keep it simple for now.
# core/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class UserProfile(AbstractUser):
pass
class Todo(models.Model):
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
is_completed = models.BooleanField(default=False)
def __str__(self):
return self.title
Let's run migrations for our new model:
❯ uv run python manage.py makemigrations
migrations for 'core':
core/migrations/0002_todo.py
+ create model todo
❯ uv run python manage.py migrate
operations to perform:
apply all migrations: admin, auth, contenttypes, core, sessions
running migrations:
applying core.0002_todo... ok
Writing Our First Test
Let's write our first test for the project. We want to ensure that users can only see their own todo items and not those of other users.
To aid in writing our tests, we'll add new development dependencies to our project: model-bakery, which simplifies the process of creating dummy Django model instances, and pytest-django.
❯ uv add model-bakery pytest-django --dev resolved 27 packages in 425ms installed 2 packages in 12ms + model-bakery==1.20.0 + pytest-django==4.9.0
In pyproject.toml, we need to configure pytest by adding a few lines at the end of the file:
# pyproject.toml # new [tool.pytest.ini_options] django_settings_module = "todomx.settings" python_files = ["test_*.py", "*_test.py", "testing/python/*.py"]
Now let's write our first test to ensure that users can only access their own todo items.
# core/tests/test_todo_model.py
import pytest
@pytest.mark.django_db
class TestTodoModel:
def test_todo_items_are_associated_to_users(self, make_todo, make_user):
[user1, user2] = make_user(_quantity=2)
for i in range(3):
make_todo(user=user1, title=f"user1 todo {i}")
make_todo(user=user2, title="user2 todo")
assert {todo.title for todo in user1.todos.all()} == {
"user1 todo 0",
"user1 todo 1",
"user1 todo 2",
}
assert {todo.title for todo in user2.todos.all()} == {"user2 todo"}
We use a conftest.py file in pytest to hold all the fixtures we plan to use in our tests. The model_bakery library makes creating instances of userprofile and todo simple with minimal boilerplate.
#core/tests/conftest.py
import pytest
from model_bakery import baker
@pytest.fixture
def make_user(django_user_model):
def _make_user(**kwargs):
return baker.make("core.userprofile", **kwargs)
return _make_user
@pytest.fixture
def make_todo(make_user):
def _make_todo(user=None, **kwargs):
return baker.make("core.todo", user=user or make_user(), **kwargs)
return _make_todo
Let's run the tests!
❯ uv run pytest
test session starts (platform: darwin, python 3.12.8, pytest 8.3.4, pytest-sugar 1.0.0)
django: version: 5.1.4, settings: todomx.settings (from ini)
configfile: pyproject.toml
plugins: sugar-1.0.0, django-4.9.0
collected 1 item
core/tests/test_todo_model.py ✓ 100% ██████████
results (0.25s):
1 passed
Registering the Todos Admin Page
Finally, we can register an admin page for it:
# core/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Todo, UserProfile admin.site.register(UserProfile, UserAdmin) admin.site.register(Todo)
We can now add some todos from the admin!

If you want to see the entire code before the end of Part 2, you can check it out on the Part 02 branch on github.
本篇关于《使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
【召回】新能源大厂再次召回 70万辆汽车;
- 上一篇
- 【召回】新能源大厂再次召回 70万辆汽车;
- 下一篇
- 浙江光昊光电完成A轮融资,加速OLED关键功能层材料研发和产业化进程
-
- 文章 · python教程 | 4小时前 |
- Python contextvars 为什么能隔离并发请求上下文
- 202浏览 收藏
-
- 文章 · python教程 | 8小时前 | Python教程 · 静态类型检查 异步方法 Python Protocol 结构类型 Awaitable
- Python Protocol 怎样描述带异步方法的结构类型
- 363浏览 收藏
-
- 文章 · python教程 | 11小时前 | Python教程 · InitVar __post_init__ Python dataclasses.replace 数据类复制
- Python dataclasses.replace 遇到 InitVar 时怎样传递参数
- 381浏览 收藏
-
- 文章 · python教程 | 13小时前 | python · pathlib ·
- Python importlib.resources.as_file 的临时路径何时失效
- 318浏览 收藏
-
- 文章 · python教程 | 15小时前 | SQLite · Python教程 · Python sqlite3 Connection.backup 进度回调 SQLite备份
- Python sqlite3 备份进度回调怎样判断剩余页数
- 264浏览 收藏
-
- 文章 · python教程 | 17小时前 | python · 内存优化 · Python教程 · 文件读取 大文件处理 Python mmap 分段映射 ALLOCATIONGRANULARITY
- Python mmap 怎样分段处理超过内存的大文件
- 146浏览 收藏
-
- 文章 · python教程 | 19小时前 | python · Python 二进制协议 零拷贝 memoryview
- Python memoryview 如何零拷贝切片二进制协议数据
- 225浏览 收藏
-
- 文章 · python教程 | 21小时前 | 并发控制 · Python教程 · asyncio · 虚假唤醒 wait_for Python asyncio asyncio.Condition 异步同步
- Python asyncio.Condition.wait_for 如何处理虚假唤醒
- 478浏览 收藏
-
- 文章 · python教程 | 23小时前 |
- Python ExceptionGroup 派生新组时如何保留异常元数据
- 417浏览 收藏
-
- 文章 · python教程 | 1天前 | 异常处理 · 并发编程 · Python教程 · asyncio · asyncio 结构化并发 ExceptionGroup except* Python TaskGroup
- Python TaskGroup 如何汇总多个子任务异常
- 208浏览 收藏
-
- 文章 · python教程 | 1天前 | 并发编程 · 工程实践 · Python教程 · 多进程日志 QueueListener multiprocessing.Queue RotatingFileHandler Python QueueHandler
- Python 日志 QueueHandler 解决多进程写入争用
- 186浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 395次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 476次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 481次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 426次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 251次使用
-
- Python sqlite3 Connection serialize 怎么导出数据库快照:备份窗口、内存占用与恢复校验
- 2026-08-26 501浏览
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览
-
- TensorFlow模型部署为API的TF Serving方法
- 2026-05-26 501浏览
-
- Python字符串编码转换:encode与decode详解
- 2026-05-16 501浏览
-
- TensorFlow裁剪无用算子方法详解
- 2026-05-15 501浏览
