シリーズのパート 3 へようこそ!この一連の記事では、バックエンドに Django を使用して、私自身が HTMX について学習したことを文書化しています。
このシリーズに参加したばかりの場合は、最初にパート 1 とパート 2 を確認するとよいでしょう。
テンプレートとビューの作成
まず、ベース テンプレートと、データベース内にある Todo をリストするインデックス ビューを指すインデックス テンプレートを作成します。 Todo の見栄えを良くするために、Tailwind CSS の拡張である DaisyUI を使用します。
これは、ビューが設定され、HTMLX を追加する前のページの外観です。
ビューと 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 とビューにリダイレクトされるだけです。これにより、将来的にアプリに何らかのランディング ページを自由に実装できるようになります。
タスクビューにはログインが必要で、コンテキスト内で 2 つの属性を返します。ユーザーのフルネーム (必要に応じてユーザー名と合体)、および ToDo アイテム (作成日順にソート) (将来)。
次に、テンプレートを追加しましょう。 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>タスク テンプレートでは、各 ToDo アイテムをインライン部分テンプレートとして定義します。ページをリロードしても、視覚的な違いは何もないはずです。<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 と、対象の項目の名前と一致するコンテキストを参照して、パーシャルのみを返しています。 task.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 を使用した To-Do アプリの作成 - パート フロントエンドの作成と HTMX の追加の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

この記事では、Pythonライブラリである美しいスープを使用してHTMLを解析する方法について説明します。 find()、find_all()、select()、およびget_text()などの一般的な方法は、データ抽出、多様なHTML構造とエラーの処理、および代替案(SEL

Pythonオブジェクトのシリアル化と脱介入は、非自明のプログラムの重要な側面です。 Pythonファイルに何かを保存すると、構成ファイルを読み取る場合、またはHTTPリクエストに応答する場合、オブジェクトシリアル化と脱滑り化を行います。 ある意味では、シリアル化と脱派化は、世界で最も退屈なものです。これらすべての形式とプロトコルを気にするのは誰ですか? Pythonオブジェクトを維持またはストリーミングし、後で完全に取得したいと考えています。 これは、概念レベルで世界を見るのに最適な方法です。ただし、実用的なレベルでは、選択したシリアル化スキーム、形式、またはプロトコルは、プログラムの速度、セキュリティ、メンテナンスの自由、およびその他の側面を決定する場合があります。

この記事では、深い学習のためにTensorflowとPytorchを比較しています。 関連する手順、データの準備、モデルの構築、トレーニング、評価、展開について詳しく説明しています。 特に計算グラップに関して、フレームワーク間の重要な違い

Pythonの統計モジュールは、強力なデータ統計分析機能を提供して、生物統計やビジネス分析などのデータの全体的な特性を迅速に理解できるようにします。データポイントを1つずつ見る代わりに、平均や分散などの統計を見て、無視される可能性のある元のデータの傾向と機能を発見し、大きなデータセットをより簡単かつ効果的に比較してください。 このチュートリアルでは、平均を計算し、データセットの分散の程度を測定する方法を説明します。特に明記しない限り、このモジュールのすべての関数は、単に平均を合計するのではなく、平均()関数の計算をサポートします。 浮動小数点数も使用できます。 ランダムをインポートします インポート統計 fractiから

このチュートリアルは、単純なツリーナビゲーションを超えたDOM操作に焦点を当てた、美しいスープの以前の紹介に基づいています。 HTML構造を変更するための効率的な検索方法と技術を探ります。 1つの一般的なDOM検索方法はExです

この記事では、numpy、pandas、matplotlib、scikit-learn、tensorflow、django、flask、and requestsなどの人気のあるPythonライブラリについて説明し、科学的コンピューティング、データ分析、視覚化、機械学習、Web開発、Hの使用について説明します。

この記事では、コマンドラインインターフェイス(CLI)の構築に関するPython開発者をガイドします。 Typer、Click、Argparseなどのライブラリを使用して、入力/出力の処理を強調し、CLIの使いやすさを改善するためのユーザーフレンドリーな設計パターンを促進することを詳述しています。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

ホットトピック



