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

wufei123 2025-01-05 阅读:9 评论:0
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...

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!

使用 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.

以上就是使用 Django 和 HTMX 创建 To-Do 应用程序 - 使用 TDD 添加 Todo 模型部分的详细内容,更多请关注知识资源分享宝库其它相关文章!

版权声明

本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com

分享:

扫一扫在手机阅读、分享本文

发表评论
热门文章
  • 华为 Mate 70 性能重回第一梯队 iPhone 16 最后一块遮羞布被掀

    华为 Mate 70 性能重回第一梯队 iPhone 16 最后一块遮羞布被掀
    华为 mate 70 或将首发麒麟新款处理器,并将此前有博主爆料其性能跑分将突破110万,这意味着 mate 70 性能将重新夺回第一梯队。也因此,苹果 iphone 16 唯一能有一战之力的性能,也要被 mate 70 拉近不少了。 据悉,华为 Mate 70 性能会大幅提升,并且销量相比 Mate 60 预计增长40% - 50%,且备货充足。如果 iPhone 16 发售日期与 Mate 70 重合,销量很可能被瞬间抢购。 不过,iPhone 16 还有一个阵地暂时难...
  • 惠普新款战 99 笔记本 5 月 20 日开售:酷睿 Ultra / 锐龙 8040,4999 元起

    惠普新款战 99 笔记本 5 月 20 日开售:酷睿 Ultra / 锐龙 8040,4999 元起
    本站 5 月 14 日消息,继上线官网后,新款惠普战 99 商用笔记本现已上架,搭载酷睿 ultra / 锐龙 8040处理器,最高可选英伟达rtx 3000 ada 独立显卡,售价 4999 元起。 战 99 锐龙版 R7-8845HS / 16GB / 1TB:4999 元 R7-8845HS / 32GB / 1TB:5299 元 R7-8845HS / RTX 4050 / 32GB / 1TB:7299 元 R7 Pro-8845HS / RTX 2000 Ada...
  • 酷凛 ID-COOLING 推出霜界 240/360 一体水冷散热器,239/279 元

    酷凛 ID-COOLING 推出霜界 240/360 一体水冷散热器,239/279 元
    本站 5 月 16 日消息,酷凛 id-cooling 近日推出霜界 240/360 一体式水冷散热器,采用黑色无光低调设计,分别定价 239/279 元。 本站整理霜界 240/360 散热器规格如下: 酷凛宣称这两款水冷散热器搭载“自研新 V7 水泵”,采用三相六极马达和改进的铜底方案,缩短了水流路径,相较上代水泵进一步提升解热能力。 霜界 240/360 散热器的水泵为定速 2800 RPM 设计,噪声 28db (A)。 两款一体式水冷散热器采用 27mm 厚冷排,...
  • Nginx服务器的HTTP/2协议支持和性能提升技巧介绍

    Nginx服务器的HTTP/2协议支持和性能提升技巧介绍
    Nginx服务器的HTTP/2协议支持和性能提升技巧介绍 引言:随着互联网的快速发展,人们对网站速度的要求越来越高。为了提供更快的网站响应速度和更好的用户体验,Nginx服务器的HTTP/2协议支持和性能提升技巧变得至关重要。本文将介绍如何配置Nginx服务器以支持HTTP/2协议,并提供一些性能提升的技巧。 一、HTTP/2协议简介:HTTP/2协议是HTTP协议的下一代标准,它在传输层使用二进制格式进行数据传输,相比之前的HTTP1.x协议,HTTP/2协议具有更低的延...
  • 两个表格切换的快捷键是什么

    两个表格切换的快捷键是什么
    两个表格切换的快捷键是“ctrl+pageup”和“ctrl+pagedown”,按键盘上的“ctrl+pageup”键是向右切换表格,按“ctrl+pagedown”键是向左切换表格。 本教程操作环境:windows7系统、Microsoft Office Excel2010版、Dell G3电脑。 两个工作表之间切换是Ctrl+Tab,两个工作簿之间切换是Ctrl+PageUP和Ctrl+PageDown。 打开Excel表格,打开几个工作簿。 按键盘上的Ctrl+P...