欢迎来到我们系列的第三部分!在本系列文章中,我记录了自己对 HTMX 的学习,使用 Django 作为后端。
如果您刚刚接触该系列,您可能需要先查看第一部分和第二部分。
创建模板和视图
我们将首先创建一个基本模板和一个指向索引视图的索引模板,该索引视图将列出数据库中的待办事项。我们将使用 DaisyUI(Tailwind CSS 的扩展)来使 Todos 看起来更漂亮。
这是设置视图后、添加 HTMX 之前页面的样子:
添加视图和 URL
首先,我们需要更新项目根目录中的 urls.py 文件,以包含我们将在“核心”应用程序中定义的 url:
# todomx/urls.py from django.contrib import admin from django.urls import include, path # <p>然后,我们为应用程序定义新的 URL,添加新文件 core/urls.py:<br> </p> <pre class="brush:php;toolbar:false"># core/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("tasks/", views.tasks, name="tasks"), ]
现在我们可以创建相应的视图了,在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)
这里有一些有趣的事情:我们的索引路由(主页)将仅重定向到任务 URL 和视图。这将使我们能够在未来自由地为应用程序实现某种登陆页面。
任务视图需要登录,并在上下文中返回两个属性:用户的全名(如果需要的话会合并到用户名)和待办事项,按创建日期排序(我们可以在未来)。
现在让我们添加模板。我们将为整个应用程序提供一个基本模板,其中包括 Tailwind CSS 和 DaisyUI,以及任务视图的模板。
<!-- core/templates/_base.html --> <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 %} <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
按照安装说明,我们应该更新我们的settings.py 文件
INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "core", "template_partials", # <p>在我们的任务模板中,我们将每个待办事项定义为内联部分模板。如果我们重新加载页面,它不应该有任何视觉差异。<br> </p> <pre class="brush:php;toolbar:false"><!-- 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 %}
在 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"), path("tasks/<task_id>/", views.toggle_todo, name="toggle_todo"), # <p>然后,在core/views.py上,我们添加相应的视图:<br> </p> <pre class="brush:php;toolbar:false"># 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 # <p>在 return 语句中,我们可以看到如何利用模板部分:通过引用其名称 todo-item-partial 以及与我们要处理的项目名称相匹配的上下文,我们仅返回部分在tasks.html中的循环中进行迭代。</p> <p>我们现在可以测试打开和关闭该项目:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284449958.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>看起来我们只是在做一些客户端工作,但是检查浏览器中的网络工具向我们展示了如何分派 PUT 请求并返回部分 HTML:</p><p>PUT 请求 </p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284544580.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>回复</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173609284614077.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX"></p> <p>我们的应用程序现已 HTMX 化!您可以在此处查看最终代码。在第 4 部分中,我们将添加添加和删除任务的功能。</p>
以上是使用 Django 和 HTMX 创建待办事项应用程序 - 创建前端并添加 HTMX 部分的详细内容。更多信息请关注PHP中文网其他相关文章!

本文讨论了Python版本3.10中介绍的新“匹配”语句,该语句与其他语言相同。它增强了代码的可读性,并为传统的if-elif-el提供了性能优势

Python中的功能注释将元数据添加到函数中,以进行类型检查,文档和IDE支持。它们增强了代码的可读性,维护,并且在API开发,数据科学和图书馆创建中至关重要。

本文讨论了Python中的单位测试,其好处以及如何有效编写它们。它突出显示了诸如UNITSEST和PYTEST等工具进行测试。

文章讨论了Python的\ _ \ _ Init \ _ \ _()方法和Self在初始化对象属性中的作用。还涵盖了其他类方法和继承对\ _ \ _ Init \ _ \ _()的影响。

本文讨论了python中@classmethod,@staticmethod和实例方法之间的差异,详细介绍了它们的属性,用例和好处。它说明了如何根据所需功能选择正确的方法类型和DA

Inpython,YouAppendElementStoAlistusingTheAppend()方法。1)useappend()forsingleelements:my_list.append(4).2)useextend()orextend()或= formultiplelements:my_list.extend.extend(emote_list)ormy_list = [4,5,6] .3)useInsert()forspefificpositions:my_list.insert(1,5).beaware


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

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

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

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