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

    按照安裝說(shuō)明,我們應(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ù)範(fàn)本中,我們將每個(gè)待辦事項(xiàng)定義為內(nèi)嵌部分範(fàn)本。如果我們重新加載頁(yè)面,它不應(yīng)該有任何視覺(jué)差異。
    \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成人天堂

    首頁(yè) 後端開發(fā) Python教學(xué) 使用 Django 和 HTMX 建立待辦事項(xiàng)應(yīng)用程式 - 建立前端並新增 HTMX 部分

    使用 Django 和 HTMX 建立待辦事項(xiàng)應(yīng)用程式 - 建立前端並新增 HTMX 部分

    Jan 06, 2025 am 12:00 AM

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

    建立模板和視圖

    我們將首先建立一個(gè)基本模板和一個(gè)指向索引視圖的索引模板,該索引視圖將列出資料庫(kù)中的待辦事項(xiàng)。我們將使用 DaisyUI(Tailwind CSS 的擴(kuò)充功能)來(lái)使 Todos 看起來(lái)更漂亮。

    這是設(shè)定視圖後、新增 HTMX 之前頁(yè)面的樣子:

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

    新增視圖和 URL

    首先,我們需要更新專案根目錄中的 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)在我們可以建立對(duì)應(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)
    
    

    這裡有一些有趣的事情:我們的索引路由(主頁(yè))將只重定向到任務(wù) URL 和視圖。這將使我們能夠在未來(lái)自由地為應(yīng)用程式實(shí)現(xiàn)某種登陸頁(yè)面。

    任務(wù)視圖需要登錄,並在上下文中傳回兩個(gè)屬性:使用者的全名(如果需要的話會(huì)合併到使用者名稱)和待辦事項(xiàng),按建立日期排序(我們可以在未來(lái))。

    現(xiàn)在讓我們來(lái)新增模板。我們將為整個(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
    

    按照安裝說(shuō)明,我們應(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ù)範(fàn)本中,我們將每個(gè)待辦事項(xiàng)定義為內(nèi)嵌部分範(fàn)本。如果我們重新加載頁(yè)面,它不應(yīng)該有任何視覺(jué)差異。

    <!-- 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上,我們加入對(duì)應(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 語(yǔ)句中,我們可以看到如何利用範(fàn)本部分:透過(guò)引用其名稱todo-item-partial 以及與我們要處理的項(xiàng)目名稱相符的上下文,我們只傳回部分在tasks.html中的循環(huán)中進(jìn)行迭代。

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

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

    看起來(lái)我們只是在做一些客戶端工作,但是檢查瀏覽器中的網(wǎng)頁(yè)工具向我們展示瞭如何分派 PUT 請(qǐng)求並返回部分 HTML:

    PUT 請(qǐng)求

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

    回覆

    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 建立待辦事項(xiàng)應(yīng)用程式 - 建立前端並新增 HTMX 部分的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

    本網(wǎng)站聲明
    本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)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脫衣器

    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

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

    SublimeText3 Mac版

    SublimeText3 Mac版

    神級(jí)程式碼編輯軟體(SublimeText3)

    Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

    多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實(shí)現(xiàn)”,允許統(tǒng)一處理不同類型的對(duì)象。 1.多態(tài)通過(guò)方法重寫實(shí)現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實(shí)現(xiàn)。 2.多態(tài)的實(shí)際用途包括簡(jiǎn)化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪製程序中統(tǒng)一調(diào)用draw()方法,或遊戲開發(fā)中處理不同角色的共同行為。 3.Python實(shí)現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對(duì)象實(shí)現(xiàn)相同方法即可,這稱為“鴨子類型”。 4.注意事項(xiàng)包括保持方

    我如何寫一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? 我如何寫一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? Jun 24, 2025 am 12:45 AM

    "Hello,World!"程序是用Python編寫的最基礎(chǔ)示例,用於展示基本語(yǔ)法並驗(yàn)證開發(fā)環(huán)境是否正確配置。 1.它通過(guò)一行代碼print("Hello,World!")實(shí)現(xiàn),運(yùn)行後會(huì)在控制臺(tái)輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯(cuò)誤有遺漏括號(hào)或引號(hào)、誤用大寫Print、未保存為.py格式以及運(yùn)行環(huán)境錯(cuò)誤;4.可選工具包括本地文本編輯器 終端、在線編輯器(如replit.com)

    Python中的算法是什麼?為什麼它們很重要? Python中的算法是什麼?為什麼它們很重要? Jun 24, 2025 am 12:43 AM

    AlgorithmsinPythonareessentialforefficientproblem-solvinginprogramming.Theyarestep-by-stepproceduresusedtosolvetaskslikesorting,searching,anddatamanipulation.Commontypesincludesortingalgorithmslikequicksort,searchingalgorithmslikebinarysearch,andgrap

    什麼是python的列表切片? 什麼是python的列表切片? Jun 29, 2025 am 02:15 AM

    ListslicinginPythonextractsaportionofalistusingindices.1.Itusesthesyntaxlist[start:end:step],wherestartisinclusive,endisexclusive,andstepdefinestheinterval.2.Ifstartorendareomitted,Pythondefaultstothebeginningorendofthelist.3.Commonusesincludegetting

    python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

    類方法是Python中通過(guò)@classmethod裝飾器定義的方法,其第一個(gè)參數(shù)為類本身(cls),用於訪問(wèn)或修改類狀態(tài)。它可通過(guò)類或?qū)嵗{(diào)用,影響的是整個(gè)類而非特定實(shí)例;例如在Person類中,show_count()方法統(tǒng)計(jì)創(chuàng)建的對(duì)像數(shù)量;定義類方法時(shí)需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實(shí)例方法(self參數(shù))、靜態(tài)方法(無(wú)自動(dòng)參數(shù))不同,適用於工廠方法、替代構(gòu)造函數(shù)及管理類變量等場(chǎng)景;常見用途包括從

    Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

    參數(shù)(parameters)是定義函數(shù)時(shí)的佔(zhàn)位符,而傳參(arguments)是調(diào)用時(shí)傳入的具體值。 1.位置參數(shù)需按順序傳遞,順序錯(cuò)誤會(huì)導(dǎo)致結(jié)果錯(cuò)誤;2.關(guān)鍵字參數(shù)通過(guò)參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時(shí)賦值,避免重複代碼,但應(yīng)避免使用可變對(duì)像作為默認(rèn)值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用於通用接口或裝飾器,但應(yīng)謹(jǐn)慎使用以保持可讀性。

    如何使用CSV模塊在Python中使用CSV文件? 如何使用CSV模塊在Python中使用CSV文件? Jun 25, 2025 am 01:03 AM

    Python的csv模塊提供了讀寫CSV文件的簡(jiǎn)單方法。 1.讀取CSV文件時(shí),可使用csv.reader()逐行讀取,並將每行數(shù)據(jù)作為字符串列表返回;若需通過(guò)列名訪問(wèn)數(shù)據(jù),則可用csv.DictReader(),它將每行映射為字典。 2.寫入CSV文件時(shí),使用csv.writer()並調(diào)用writerow()或writerows()方法寫入單行或多行數(shù)據(jù);若要寫入字典數(shù)據(jù),則使用csv.DictWriter(),需先定義列名並通過(guò)writeheader()寫入表頭。 3.處理邊緣情況時(shí),模塊自動(dòng)處理

    解釋Python發(fā)電機(jī)和迭代器。 解釋Python發(fā)電機(jī)和迭代器。 Jul 05, 2025 am 02:55 AM

    迭代器是實(shí)現(xiàn)__iter__()和__next__()方法的對(duì)象,生成器是簡(jiǎn)化版的迭代器,通過(guò)yield關(guān)鍵字自動(dòng)實(shí)現(xiàn)這些方法。 1.迭代器每次調(diào)用next()返回一個(gè)元素,無(wú)更多元素時(shí)拋出StopIteration異常。 2.生成器通過(guò)函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無(wú)限序列。 3.處理已有集合時(shí)用迭代器,動(dòng)態(tài)生成大數(shù)據(jù)或需惰性求值時(shí)用生成器,如讀取大文件時(shí)逐行加載。注意:列表等可迭代對(duì)像不是迭代器,迭代器到盡頭後需重新創(chuàng)建,生成器只能遍歷一次。

    See all articles