0

0

使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分

DDD

DDD

发布时间:2025-01-02 18:56:39

|

535人浏览过

|

来源于php中文网

原创

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:

Designs.ai
Designs.ai

AI设计工具

下载
# 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!

使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分

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.

相关专题

更多
java中boolean的用法
java中boolean的用法

在Java中,boolean是一种基本数据类型,它只有两个可能的值:true和false。boolean类型经常用于条件测试,比如进行比较或者检查某个条件是否满足。想了解更多java中boolean的相关内容,可以阅读本专题下面的文章。

349

2023.11.13

java boolean类型
java boolean类型

本专题整合了java中boolean类型相关教程,阅读专题下面的文章了解更多详细内容。

27

2025.11.30

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

746

2023.08.22

vb中怎么连接access数据库
vb中怎么连接access数据库

vb中连接access数据库的步骤包括引用必要的命名空间、创建连接字符串、创建连接对象、打开连接、执行SQL语句和关闭连接。本专题为大家提供连接access数据库相关的文章、下载、课程内容,供大家免费下载体验。

323

2023.10.09

vb连接access数据库的方法
vb连接access数据库的方法

vb连接access数据库方法:1、使用ADO连接,首先导入System.Data.OleDb模块,然后定义一个连接字符串,接着创建一个OleDbConnection对象并使用Open() 方法打开连接;2、使用DAO连接,首先导入 Microsoft.Jet.OLEDB模块,然后定义一个连接字符串,接着创建一个JetConnection对象并使用Open()方法打开连接即可。

397

2023.10.16

asp连接access数据库的方法
asp连接access数据库的方法

连接的方法:1、使用ADO连接数据库;2、使用DSN连接数据库;3、使用连接字符串连接数据库。想了解更详细的asp连接access数据库的方法,可以阅读本专题下面的文章。

120

2023.10.18

access和trunk端口的区别
access和trunk端口的区别

access和trunk端口的区别是Access端口用于连接终端设备,提供单个VLAN的接入,而Trunk端口用于连接交换机之间,提供多个VLAN的传输;Access端口只传输属于指定VLAN的数据,而Trunk端口可以传输多个VLAN的数据,并使用VLAN标签进行区分。想了解更多access和trunk端口相关内容,可以阅读本专题下面的文章。

326

2023.10.31

access怎么导入数据
access怎么导入数据

access导入数据步骤:1. 选择数据源 2. 选择要导入的文件 3. 指定导入选项 4. 选择导入目标 5. 预览数据 6. 导入数据即可。想了解更多access的相关内容,可以阅读本专题下面的文章。

438

2024.04.10

高德地图升级方法汇总
高德地图升级方法汇总

本专题整合了高德地图升级相关教程,阅读专题下面的文章了解更多详细内容。

43

2026.01.16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 3.8万人学习

Django 教程
Django 教程

共28课时 | 3.2万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号