<button id="sek6k"><object id="sek6k"></object></button>
<nav id="sek6k"><center id="sek6k"></center></nav>
\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

インストール手順に従って、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

タスク テンプレートでは、各 ToDo アイテムをインライン部分テンプレートとして定義します。ページをリロードしても、視覚的な違いは何もないはずです。
\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成人天堂

ホームページ バックエンド開発 Python チュートリアル Django と HTMX を使用した To-Do アプリの作成 - パート フロントエンドの作成と HTMX の追加

Django と HTMX を使用した To-Do アプリの作成 - パート フロントエンドの作成と HTMX の追加

Jan 06, 2025 am 12:00 AM

シリーズのパート 3 へようこそ!この一連の記事では、バックエンドに Django を使用して、私自身が HTMX について學(xué)習(xí)したことを文書化しています。
このシリーズに參加したばかりの場合は、最初にパート 1 とパート 2 を確認(rèn)するとよいでしょう。

テンプレートとビューの作成

まず、ベース テンプレートと、データベース內(nèi)にある Todo をリストするインデックス ビューを指すインデックス テンプレートを作成します。 Todo の見栄えを良くするために、Tailwind CSS の拡張である DaisyUI を使用します。

これは、ビューが設(shè)定され、HTMLX を追加する前のページの外観です。

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

ビューと URL の追加

まず、プロジェクトのルートにある urls.py ファイルを更新して、「コア」アプリに定義する 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
]

次に、アプリの新しい 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"),
]

これで、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)

ここで興味深い點(diǎn)がいくつかあります。インデックス ルート (ホームページ) はタスクの URL とビューにリダイレクトされるだけです。これにより、將來的にアプリに何らかのランディング ページを自由に実裝できるようになります。

タスクビューにはログインが必要で、コンテキスト內(nèi)で 2 つの屬性を返します。ユーザーのフルネーム (必要に応じてユーザー名と合體)、および ToDo アイテム (作成日順にソート) (將來)。

次に、テンプレートを追加しましょう。 Tailwind CSS と DaisyUI を含むアプリ全體の基本テンプレートと、タスク ビューのテンプレートを用意します。

<!-- 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

インストール手順に従って、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
]

タスク テンプレートでは、各 ToDo アイテムをインライン部分テンプレートとして定義します。ページをリロードしても、視覚的な違いは何もないはずです。

<!-- 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 に対応するビューを追加します。

# 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 ステートメントでは、テンプレートのパーシャルをどのように利用できるかを確認(rèn)できます。名前 todo-item-partial と、対象の項(xiàng)目の名前と一致するコンテキストを參照して、パーシャルのみを返しています。 task.html.

のループ內(nèi)で反復(fù)処理します。

項(xiàng)目のオンとオフの切り替えをテストできるようになりました:

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

クライアント側(cè)の作業(yè)を行っているだけのように見えますが、ブラウザでネットワーク ツールを調(diào)べると、PUT リクエストをディスパッチし、部分的な HTML を返していることがわかります。

PUT リクエスト

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

私たちのアプリは HTMX 対応になりました!最終的なコードはここで確認(rèn)できます。パート 4 では、タスクを追加および削除する機(jī)能を追加します。

以上がDjango と HTMX を使用した To-Do アプリの作成 - パート フロントエンドの作成と HTMX の追加の詳細(xì)內(nèi)容です。詳細(xì)については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Pythonの不適格またはPytestフレームワークは、自動(dòng)テストをどのように促進(jìn)しますか? Pythonの不適格またはPytestフレームワークは、自動(dòng)テストをどのように促進(jìn)しますか? Jun 19, 2025 am 01:10 AM

Pythonの不適格でPytestは、自動(dòng)テストの書き込み、整理、および実行を簡素化する2つの広く使用されているテストフレームワークです。 1.両方とも、テストケースの自動(dòng)発見をサポートし、明確なテスト構(gòu)造を提供します。 pytestはより簡潔で、テスト\ _から始まる関數(shù)が必要です。 2。それらはすべて組み込みのアサーションサポートを持っています:Unittestはアサートエクイアル、アサートトルー、およびその他の方法を提供しますが、Pytestは拡張されたアサートステートメントを使用して障害の詳細(xì)を自動(dòng)的に表示します。 3.すべてがテストの準(zhǔn)備とクリーニングを処理するためのメカニズムを持っています:un

Pythonは、NumpyやPandasなどのライブラリとのデータ分析と操作にどのように使用できますか? Pythonは、NumpyやPandasなどのライブラリとのデータ分析と操作にどのように使用できますか? Jun 19, 2025 am 01:04 AM

pythonisidealfordataanalysisduetonumpyandpandas.1)numpyexcelsatnumericalcompitations withfast、多次元路面およびベクトル化された分離likenp.sqrt()

動(dòng)的なプログラミング技術(shù)とは何ですか?また、Pythonでそれらを使用するにはどうすればよいですか? 動(dòng)的なプログラミング技術(shù)とは何ですか?また、Pythonでそれらを使用するにはどうすればよいですか? Jun 20, 2025 am 12:57 AM

動(dòng)的プログラミング(DP)は、複雑な問題をより単純なサブ問題に分解し、結(jié)果を保存して繰り返し計(jì)算を回避することにより、ソリューションプロセスを最適化します。主な方法は2つあります。1。トップダウン(暗記):問題を再帰的に分解し、キャッシュを使用して中間結(jié)果を保存します。 2。ボトムアップ(表):基本的な狀況からソリューションを繰り返し構(gòu)築します。フィボナッチシーケンス、バックパッキングの問題など、最大/最小値、最適なソリューション、または重複するサブ問題が必要なシナリオに適しています。Pythonでは、デコレータまたはアレイを通じて実裝でき、再帰的な関係を特定し、ベンチマークの狀況を定義し、空間の複雑さを最適化することに注意する必要があります。

__iter__と__next__を使用してPythonにカスタムイテレーターを?qū)g裝するにはどうすればよいですか? __iter__と__next__を使用してPythonにカスタムイテレーターを?qū)g裝するにはどうすればよいですか? Jun 19, 2025 am 01:12 AM

カスタムイテレーターを?qū)g裝するには、クラス內(nèi)の__iter__および__next__メソッドを定義する必要があります。 __iter__メソッドは、ループなどの反復(fù)環(huán)境と互換性があるように、通常は自己の反復(fù)オブジェクト自體を返します。 __next__メソッドは、各反復(fù)の値を制御し、シーケンスの次の要素を返し、アイテムがもうない場合、停止例外をスローする必要があります。 statusステータスを正しく追跡する必要があり、無限のループを避けるために終了條件を設(shè)定する必要があります。 fileファイルラインフィルタリングなどの複雑なロジック、およびリソースクリーニングとメモリ管理に注意を払ってください。 simple単純なロジックについては、代わりにジェネレーター関數(shù)の収率を使用することを検討できますが、特定のシナリオに基づいて適切な方法を選択する必要があります。

Pythonプログラミング言語とそのエコシステムの新たな傾向または將來の方向性は何ですか? Pythonプログラミング言語とそのエコシステムの新たな傾向または將來の方向性は何ですか? Jun 19, 2025 am 01:09 AM

Pythonの將來の傾向には、パフォーマンスの最適化、より強(qiáng)力なタイププロンプト、代替ランタイムの増加、およびAI/MLフィールドの継続的な成長が含まれます。第一に、CPYTHONは最適化を続け、スタートアップのより速い時(shí)間、機(jī)能通話の最適化、および提案された整數(shù)操作を通じてパフォーマンスを向上させ続けています。第二に、タイプのプロンプトは、コードセキュリティと開発エクスペリエンスを強(qiáng)化するために、言語とツールチェーンに深く統(tǒng)合されています。第三に、PyscriptやNuitkaなどの代替のランタイムは、新しい機(jī)能とパフォーマンスの利點(diǎn)を提供します。最後に、AIとデータサイエンスの分野は拡大し続けており、新興図書館はより効率的な開発と統(tǒng)合を促進(jìn)します。これらの傾向は、Pythonが常に技術(shù)の変化に適応し、その主要な位置を維持していることを示しています。

ソケットを使用してPythonでネットワークプログラミングを?qū)g行するにはどうすればよいですか? ソケットを使用してPythonでネットワークプログラミングを?qū)g行するにはどうすればよいですか? Jun 20, 2025 am 12:56 AM

Pythonのソケットモジュールは、クライアントおよびサーバーアプリケーションの構(gòu)築に適した低レベルのネットワーク通信機(jī)能を提供するネットワークプログラミングの基礎(chǔ)です?;镜膜蔜CPサーバーを設(shè)定するには、Socket.Socket()を使用してオブジェクトを作成し、アドレスとポートをバインドし、.listen()を呼び出して接続をリッスンし、.accept()を介してクライアント接続を受け入れる必要があります。 TCPクライアントを構(gòu)築するには、ソケットオブジェクトを作成し、.connect()を呼び出してサーバーに接続する必要があります。次に、.sendall()を使用してデータと.recv()を送信して応答を受信します。複數(shù)のクライアントを処理するには、1つを使用できます。スレッド:接続するたびに新しいスレッドを起動(dòng)します。 2。非同期I/O:たとえば、Asyncioライブラリは非ブロッキング通信を?qū)g現(xiàn)できます。注意すべきこと

Pythonクラスの多型 Pythonクラスの多型 Jul 05, 2025 am 02:58 AM

Pythonオブジェクト指向プログラミングのコアコンセプトであるPythonは、「1つのインターフェイス、複數(shù)の実裝」を指し、異なるタイプのオブジェクトの統(tǒng)一処理を可能にします。 1。多型は、メソッドの書き換えを通じて実裝されます。サブクラスは、親クラスの方法を再定義できます。たとえば、Animal ClassのSOCK()方法は、犬と貓のサブクラスに異なる実裝を持っています。 2.多型の実用的な用途には、グラフィカルドローイングプログラムでdraw()メソッドを均一に呼び出すなど、コード構(gòu)造を簡素化し、スケーラビリティを向上させる、ゲーム開発における異なる文字の共通の動(dòng)作の処理などが含まれます。 3. Pythonの実裝多型を満たす必要があります:親クラスはメソッドを定義し、子クラスはメソッドを上書きしますが、同じ親クラスの継承は必要ありません。オブジェクトが同じ方法を?qū)g裝する限り、これは「アヒル型」と呼ばれます。 4.注意すべきことには、メンテナンスが含まれます

Pythonでリストをスライスするにはどうすればよいですか? Pythonでリストをスライスするにはどうすればよいですか? Jun 20, 2025 am 12:51 AM

Pythonリストスライスに対するコアの答えは、[start:end:step]構(gòu)文をマスターし、その動(dòng)作を理解することです。 1.リストスライスの基本形式はリスト[start:end:step]です。ここで、開始は開始インデックス(含まれています)、endはend index(含まれていません)、ステップはステップサイズです。 2。デフォルトで開始を省略して、0から開始を開始し、デフォルトで終了して終了し、デフォルトでステップを1に省略します。 3。my_list[:n]を使用して最初のnアイテムを取得し、my_list [-n:]を使用して最後のnアイテムを取得します。 4.ステップを使用して、my_list [:: 2]などの要素をスキップして、均一な數(shù)字と負(fù)のステップ値を取得できます。 5.一般的な誤解には、終了インデックスが含まれません

See all articles