• <i id="zpa0u"></i><thead id="zpa0u"></thead>
    <li id="zpa0u"></li>

          \n\n\n\n

          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>\n\n

          We're using the beta version of DaisyUI 5.0, which includes a new list component which suits our todo items fine.
          \n<\/p>\n\n

          \n\n{% extends \"_base.html\" %}\n\n{% block content %}\n
          \n\n\n\n

          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>\n\n

          We're now ready to add some HTMX to the app, to toggle the completion of the item<\/p>\n\n

          \n \n \n Add inline partial templates\n<\/h2>\n\n

          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 server-driven<\/strong> updates, leveraging 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>\n\n

          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>\n\n

          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.
          \n<\/p>\n\n

          ? uv add django-template-partials\nResolved 24 packages in 435ms\nInstalled 1 package in 10ms\n + django-template-partials==24.4\n<\/pre>\n\n\n\n

          按照安裝說明,我們應(yīng)該更新我們的settings.py 文件
          \n<\/p>\n\n

          INSTALLED_APPS = [\n    \"django.contrib.admin\",\n    \"django.contrib.auth\",\n    \"django.contrib.contenttypes\",\n    \"django.contrib.sessions\",\n    \"django.contrib.messages\",\n    \"django.contrib.staticfiles\",\n    \"core\",\n    \"template_partials\",  # <-- NEW\n]\n<\/pre>\n\n\n\n

          在我們的任務(wù)模板中,我們將每個(gè)待辦事項(xiàng)定義為內(nèi)聯(lián)部分模板。如果我們重新加載頁面,它不應(yīng)該有任何視覺差異。
          \n<\/p>\n\n

          \n\n{% extends \"_base.html\" %}\n{% load partials %} \n\n{% block content %}\n
          \n\n\n\n

          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>\n\n

          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>\n\n

          \n \n \n Toggling todo items on and off with HTMX\n<\/h2>\n\n

          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>\n\n

          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:
          \n<\/p>\n\n

              \n    
          	
          
          
          
          
          
          
          

          国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

          首頁 后端開發(fā) Python教程 使用 Django 和 HTMX 創(chuàng)建待辦事項(xiàng)應(yīng)用程序 - 創(chuàng)建前端并添加 HTMX 部分

          使用 Django 和 HTMX 創(chuàng)建待辦事項(xiàng)應(yīng)用程序 - 創(chuàng)建前端并添加 HTMX 部分

          Jan 06, 2025 am 12:00 AM

          歡迎來到我們系列的第三部分!在本系列文章中,我記錄了自己對 HTMX 的學(xué)習(xí),使用 Django 作為后端。
          如果您剛剛接觸該系列,您可能需要先查看第一部分和第二部分。

          創(chuàng)建模板和視圖

          我們將首先創(chuàng)建一個(gè)基本模板和一個(gè)指向索引視圖的索引模板,該索引視圖將列出數(shù)據(jù)庫中的待辦事項(xiàng)。我們將使用 DaisyUI(Tailwind CSS 的擴(kuò)展)來使 Todos 看起來更漂亮。

          這是設(shè)置視圖后、添加 HTMX 之前頁面的樣子:

          Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

          添加視圖和 URL

          首先,我們需要更新項(xiàng)目根目錄中的 urls.py 文件,以包含我們將在“核心”應(yīng)用程序中定義的 url:

          # todomx/urls.py
          
          from django.contrib import admin
          from django.urls import include, path # <-- NEW
          
          urlpatterns = [
              path("admin/", admin.site.urls),
              path("", include("core.urls")), # <-- NEW
          ]
          

          然后,我們?yōu)閼?yīng)用程序定義新的 URL,添加新文件 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"),
          ]
          

          現(xiàn)在我們可以創(chuàng)建相應(yīng)的視圖了,在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)
          
          

          這里有一些有趣的事情:我們的索引路由(主頁)將僅重定向到任務(wù) URL 和視圖。這將使我們能夠在未來自由地為應(yīng)用程序?qū)崿F(xiàn)某種登陸頁面。

          任務(wù)視圖需要登錄,并在上下文中返回兩個(gè)屬性:用戶的全名(如果需要的話會(huì)合并到用戶名)和待辦事項(xiàng),按創(chuàng)建日期排序(我們可以在未來)。

          現(xiàn)在讓我們添加模板。我們將為整個(gè)應(yīng)用程序提供一個(gè)基本模板,其中包括 Tailwind CSS 和 DaisyUI,以及任務(wù)視圖的模板。

          <!-- core/templates/_base.html -->
          
          <!DOCTYPE html>
          <html>
            <head>
              <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 %}
            </head>
            <body>
          
          
          
          <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
          

          按照安裝說明,我們應(yīng)該更新我們的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",  # <-- NEW
          ]
          

          在我們的任務(wù)模板中,我們將每個(gè)待辦事項(xiàng)定義為內(nèi)聯(lián)部分模板。如果我們重新加載頁面,它不應(yīng)該有任何視覺差異。

          <!-- 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/<int:task_id>/", views.toggle_todo, name="toggle_todo"), # <-- NEW
          ]
          

          然后,在core/views.py上,我們添加相應(yīng)的視圖:

          # 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 # <-- NEW
          
          # ... existing code
          
          # NEW
          @login_required
          @require_http_methods(["PUT"])
          def toggle_todo(request, task_id):
              todo = request.user.todos.get(id=task_id)
              todo.is_completed = not todo.is_completed
              todo.save()
          
              return render(request, "tasks.html#todo-item-partial", {"todo": todo})
          
          

          在 return 語句中,我們可以看到如何利用模板部分:通過引用其名稱 todo-item-partial 以及與我們要處理的項(xiàng)目名稱相匹配的上下文,我們僅返回部分在tasks.html中的循環(huán)中進(jìn)行迭代。

          我們現(xiàn)在可以測試打開和關(guān)閉該項(xiàng)目:

          Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

          看起來我們只是在做一些客戶端工作,但是檢查瀏覽器中的網(wǎng)絡(luò)工具向我們展示了如何分派 PUT 請求并返回部分 HTML:

          PUT 請求

          Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

          回復(fù)

          Creating a To-Do app with Django and HTMX - Part Creating the frontend and adding HTMX

          我們的應(yīng)用程序現(xiàn)已 HTMX 化!您可以在此處查看最終代碼。在第 4 部分中,我們將添加添加和刪除任務(wù)的功能。

          以上是使用 Django 和 HTMX 創(chuàng)建待辦事項(xiàng)應(yīng)用程序 - 創(chuàng)建前端并添加 HTMX 部分的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

          本站聲明
          本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

          熱AI工具

          Undress AI Tool

          Undress AI Tool

          免費(fèi)脫衣服圖片

          Undresser.AI Undress

          Undresser.AI Undress

          人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

          AI Clothes Remover

          AI Clothes Remover

          用于從照片中去除衣服的在線人工智能工具。

          Clothoff.io

          Clothoff.io

          AI脫衣機(jī)

          Video Face Swap

          Video Face Swap

          使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

          熱工具

          記事本++7.3.1

          記事本++7.3.1

          好用且免費(fèi)的代碼編輯器

          SublimeText3漢化版

          SublimeText3漢化版

          中文版,非常好用

          禪工作室 13.0.1

          禪工作室 13.0.1

          功能強(qiáng)大的PHP集成開發(fā)環(huán)境

          Dreamweaver CS6

          Dreamweaver CS6

          視覺化網(wǎng)頁開發(fā)工具

          SublimeText3 Mac版

          SublimeText3 Mac版

          神級代碼編輯軟件(SublimeText3)

          Python Web應(yīng)用程序中有哪些常見的安全漏洞(例如XSS,SQL注入)以及如何緩解它們? Python Web應(yīng)用程序中有哪些常見的安全漏洞(例如XSS,SQL注入)以及如何緩解它們? Jun 10, 2025 am 12:13 AM

          Web應(yīng)用安全需重視,Python網(wǎng)站常見漏洞包括XSS、SQL注入、CSRF及文件上傳風(fēng)險(xiǎn)。針對XSS,應(yīng)使用模板引擎自動(dòng)轉(zhuǎn)義、過濾富文本HTML并設(shè)置CSP策略;防范SQL注入應(yīng)采用參數(shù)化查詢或ORM框架,并驗(yàn)證用戶輸入;防御CSRF需啟用CSRFToken機(jī)制并對敏感操作二次確認(rèn);文件上傳漏洞則要限制類型、重命名文件并禁止執(zhí)行權(quán)限。遵循規(guī)范與使用成熟工具可有效降低風(fēng)險(xiǎn),安全需持續(xù)關(guān)注與測試。

          Python的UNITDEST或PYTEST框架如何促進(jìn)自動(dòng)測試? Python的UNITDEST或PYTEST框架如何促進(jìn)自動(dòng)測試? Jun 19, 2025 am 01:10 AM

          Python的unittest和pytest是兩種廣泛使用的測試框架,它們都簡化了自動(dòng)化測試的編寫、組織和運(yùn)行。1.二者均支持自動(dòng)發(fā)現(xiàn)測試用例并提供清晰的測試結(jié)構(gòu):unittest通過繼承TestCase類并以test\_開頭的方法定義測試;pytest則更為簡潔,只需以test\_開頭的函數(shù)即可。2.它們都內(nèi)置斷言支持:unittest提供assertEqual、assertTrue等方法,而pytest使用增強(qiáng)版的assert語句,能自動(dòng)顯示失敗詳情。3.均具備處理測試準(zhǔn)備與清理的機(jī)制:un

          Python如何處理函數(shù)中的可變默認(rèn)參數(shù),為什么這會(huì)出現(xiàn)問題? Python如何處理函數(shù)中的可變默認(rèn)參數(shù),為什么這會(huì)出現(xiàn)問題? Jun 14, 2025 am 12:27 AM

          Python的函數(shù)默認(rèn)參數(shù)在定義時(shí)只被初始化一次,若使用可變對象(如列表或字典)作為默認(rèn)參數(shù),可能導(dǎo)致意外行為。例如,使用空列表作為默認(rèn)參數(shù)時(shí),多次調(diào)用函數(shù)會(huì)重復(fù)使用同一個(gè)列表,而非每次生成新列表。此行為引發(fā)的問題包括:1.函數(shù)調(diào)用間數(shù)據(jù)意外共享;2.后續(xù)調(diào)用結(jié)果受之前調(diào)用影響,增加調(diào)試難度;3.造成邏輯錯(cuò)誤且難以察覺;4.對新手和有經(jīng)驗(yàn)開發(fā)者均易產(chǎn)生困惑。為避免問題,最佳實(shí)踐是將默認(rèn)值設(shè)為None,并在函數(shù)內(nèi)部創(chuàng)建新對象,例如使用my_list=None代替my_list=[],并在函數(shù)中初始

          將Python應(yīng)用程序部署到生產(chǎn)環(huán)境中的考慮因素是什么? 將Python應(yīng)用程序部署到生產(chǎn)環(huán)境中的考慮因素是什么? Jun 10, 2025 am 12:14 AM

          部署Python應(yīng)用到生產(chǎn)環(huán)境需關(guān)注穩(wěn)定、安全和可維護(hù)。首先,使用Gunicorn或uWSGI替代開發(fā)服務(wù)器以支持并發(fā)處理;其次,配合Nginx做反向代理以提升性能;第三,按CPU核心數(shù)配置進(jìn)程數(shù)量以優(yōu)化資源;第四,使用虛擬環(huán)境隔離依賴并凍結(jié)版本確保一致性;第五,啟用詳細(xì)日志、集成監(jiān)控系統(tǒng)并設(shè)置報(bào)警機(jī)制便于運(yùn)維;第六,避免root權(quán)限運(yùn)行應(yīng)用、關(guān)閉調(diào)試信息并配置HTTPS保障安全;最后,通過CI/CD工具實(shí)現(xiàn)自動(dòng)化部署減少人為錯(cuò)誤。

          如何將Python用于數(shù)據(jù)分析和與Numpy和Pandas等文庫進(jìn)行操作? 如何將Python用于數(shù)據(jù)分析和與Numpy和Pandas等文庫進(jìn)行操作? Jun 19, 2025 am 01:04 AM

          pythonisidealfordataanalysisionduetonumpyandpandas.1)numpyExccelSatnumericalComputationswithFast,多dimensionalArraysAndRaysAndOrsAndOrsAndOffectorizedOperationsLikenp.sqrt()

          如何將Python與微服務(wù)體系結(jié)構(gòu)中的其他語言或系統(tǒng)集成? 如何將Python與微服務(wù)體系結(jié)構(gòu)中的其他語言或系統(tǒng)集成? Jun 14, 2025 am 12:25 AM

          Python可以很好地與其他語言和系統(tǒng)在微服務(wù)架構(gòu)中協(xié)同工作,關(guān)鍵在于各服務(wù)如何獨(dú)立運(yùn)行并有效通信。1.使用標(biāo)準(zhǔn)API和通信協(xié)議(如HTTP、REST、gRPC),Python通過Flask、FastAPI等框架構(gòu)建API,并利用requests或httpx調(diào)用其他語言服務(wù);2.借助消息代理(如Kafka、RabbitMQ、Redis)實(shí)現(xiàn)異步通信,Python服務(wù)可發(fā)布消息供其他語言消費(fèi)者處理,提升系統(tǒng)解耦、可擴(kuò)展性和容錯(cuò)性;3.通過C/C 擴(kuò)展或嵌入其他語言運(yùn)行時(shí)(如Jython),實(shí)現(xiàn)性

          如何使用__ITER__和__NEXT __在Python中實(shí)現(xiàn)自定義迭代器? 如何使用__ITER__和__NEXT __在Python中實(shí)現(xiàn)自定義迭代器? Jun 19, 2025 am 01:12 AM

          要實(shí)現(xiàn)自定義迭代器,需在類中定義__iter__和__next__方法。①__iter__方法返回迭代器對象自身,通常為self,以兼容for循環(huán)等迭代環(huán)境;②__next__方法控制每次迭代的值,返回序列中的下一個(gè)元素,當(dāng)無更多項(xiàng)時(shí)應(yīng)拋出StopIteration異常;③需正確跟蹤狀態(tài)并設(shè)置終止條件,避免無限循環(huán);④可封裝復(fù)雜邏輯如文件行過濾,同時(shí)注意資源清理與內(nèi)存管理;⑤對簡單邏輯可考慮使用生成器函數(shù)yield替代,但需結(jié)合具體場景選擇合適方式。

          列表,字典和集合綜合如何改善Python中的代碼可讀性和簡潔性? 列表,字典和集合綜合如何改善Python中的代碼可讀性和簡潔性? Jun 14, 2025 am 12:31 AM

          Python的列表、字典和集合推導(dǎo)式通過簡潔語法提升代碼可讀性和編寫效率。它們適用于簡化迭代與轉(zhuǎn)換操作,例如用單行代碼替代多行循環(huán)實(shí)現(xiàn)元素變換或過濾。1.列表推導(dǎo)式如[x2forxinrange(10)]能直接生成平方數(shù)列;2.字典推導(dǎo)式如{x:x2forxinrange(5)}清晰表達(dá)鍵值映射;3.條件篩選如[xforxinnumbersifx%2==0]使過濾邏輯更直觀;4.復(fù)雜條件亦可嵌入,如結(jié)合多條件過濾或三元表達(dá)式;但需避免過度嵌套或副作用操作,以免降低可維護(hù)性。合理使用推導(dǎo)式能在減少

          See all articles