这是我们关于如何使用 HTMX 和 Django 构建 Todo 应用程序系列的第二篇文章。单击此处查看第 1 部分。
在第 2 部分中,我们将创建 Todo 模型并通过单元测试实现其基本功能。
创建 Todo 模型
在 models.py 中,我们创建 Todo 模型及其基本属性。我们希望将 Todo 项目与 UserProfile 相关联,以便用户只能看到自己的项目。待办事项还将有一个标题和一个布尔属性 is_completed。我们对 Todo 模型有很多未来的想法,例如除了已完成或未开始之外还可以将任务设置为“正在进行”,以及截止日期,但那是以后的事了。现在让我们保持简单,尽快在屏幕上显示一些内容。
注意:在现实世界的应用程序中,我们可能应该考虑使用 UUID 作为 UserProfile 和 Todo 模型的主键,但我们现在会保持简单。
# core/models.py from django.contrib.auth.models import AbstractUser from django.db import models # <p>让我们运行新模型的迁移:<br> </p> <pre class="brush:php;toolbar:false">❯ 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
编写我们的第一个测试
让我们为我们的项目编写第一个测试。我们希望确保用户只能看到自己的待办事项,而看不到其他用户的项目。
为了帮助我们编写测试,我们将向我们的项目 model-bakery 添加新的开发依赖项,这简化了创建虚拟 Django 模型实例的过程。我们还将添加 pytest-django。
❯ uv add model-bakery pytest-django --dev Resolved 27 packages in 425ms Installed 2 packagez in 12ms + model-bakery==1.20.0 + pytest-django==4.9.0
在 pyproject.toml 中,我们需要通过在文件末尾添加一些行来配置 pytest:
# pyproject.toml # NEW [tool.pytest.ini_options] DJANGO_SETTINGS_MODULE = "todomx.settings" python_files = ["test_*.py", "*_test.py", "testing/python/*.py"]
现在让我们编写第一个测试,以确保用户只能访问自己的待办事项。
# 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"}
我们使用 pytest 中的 conftest.py 文件来存放我们计划在测试中使用的所有装置。 model_bakery 库使得使用最少的样板文件创建 UserProfile 和 Todo 的实例变得简单。
#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
让我们运行测试!
❯ 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
注册 Todos 的管理页面
最后,我们可以为其注册一个管理页面:
# core/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Todo, UserProfile # <p>我们现在可以从管理员添加一些待办事项!</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173594553634650.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Adding the Todo model with TDD"></p> <p>如果你想查看第 2 部分结束之前的整个代码,可以在 Github 的第 02 部分分支上查看。</p>
以上是使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分的详细内容。更多信息请关注PHP中文网其他相关文章!

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

WebStorm Mac版
好用的JavaScript开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

禅工作室 13.0.1
功能强大的PHP集成开发环境