ホームページ > バックエンド開発 > Python チュートリアル > HTMX と Django を使用した To-Do アプリの作成 (一部無限スクロール)

HTMX と Django を使用した To-Do アプリの作成 (一部無限スクロール)

DDD
リリース: 2025-01-06 12:41:41
オリジナル
376 人が閲覧しました

これは、Django を使用した HTMX の学習プロセスを文書化するシリーズのパート 7 です。このシリーズでは、HTMX の文書に従って、ToDo アイテムの無限スクロール機能を実装します。

シリーズの残りの部分を確認したい場合は、dev.to/rodbv で完全なリストをご覧ください。

部分テンプレートを更新して複数の項目をロードする

無限スクロールを実装する場合、いくつかの todo 項目 (項目の次の「ページ」) を返し、それらを現在持っている部分的なテンプレートにロードする必要があります。これは、部分テンプレートの構成方法を少し変更することを意味します。現在、以下の図で説明されているように設定されており、部分テンプレートは 1 つの ToDo アイテムのレンダリングを担当します。

Creating a To-Do app with HTMX and Django, part infinite scroll

for ループの周りの部分を含めて、順序を反転したいと思います。

Creating a To-Do app with HTMX and Django, part infinite scroll

テンプレート core/templates/index.html で交換を実行してみましょう:

<ul>



<p>Soon we will get back to the template to add the hx-get ... hx-trigger="revealed" bit that performs the infinite scroll, but first let's just change the view to return several items instead of  one on the toggle and create operations:<br>
</p>

<pre class="brush:php;toolbar:false">... previous code 

def _create_todo(request):
    title = request.POST.get("title")
    if not title:
        raise ValueError("Title is required")

    todo = Todo.objects.create(title=title, user=request.user)

    return render(
        request,
        "tasks.html#todo-items-partial", # <-- CHANGED
        {"todos": [todo]}, # <-- CHANGED
        status=HTTPStatus.CREATED,
    )

... previous code 


@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-items-partial",  # <-- CHANGED
        {
            "todos": [todo], # <-- CHANGED
        },
    )

ログイン後にコピー

コンテンツがまだ合格しているかどうかをチェックするテストは合格しており、ページの見た目は同じなので、無限スクロール自体を実装しても問題ありません。

無限スクロールの実装

テンプレートでは、hx-trigger="revealed" を指定して /tasks への hx-get リクエストを設定する必要があります。これは、要素が画面に表示される直前にのみ GET リクエストが起動されることを意味します。これは、リストの最後の要素の後に設定する必要があり、データのどの「ページ」をロードするかを指定する必要があることを意味します。この場合、一度に 20 個のアイテムを表示します。

Creating a To-Do app with HTMX and Django, part infinite scroll

それに応じてテンプレートを変更しましょう:

    <ul>



<p>There's an if next_page_number check around the "loading" icon at the bottom of the list, it will have two purposes: one is to indicate when we're loading more data, but more importantly, when the loader is revealed (it appears on the visible part of the page), it will trigger the hx-get call to /tasks, passing the page number to be retrieved. The attribute next_page_number will also be provided by the context</p>

<p>The directive hx-swap:outerHTML indicates that we will replace the outerHTML of this element with the set of <li>s we get from the server, which is great because not only we show the new data we got, but we also get rid of the loading icon.

<p>We can now move to the views file.</p>

<p>As a recap, here's how the GET /tasks view looks like by now; it's always returning the full template.<br>
</p>

<pre class="brush:php;toolbar:false">@require_http_methods(["GET", "POST"])
@login_required
def tasks(request):
    if request.method == "POST":
        return _create_todo(request)

    # GET /tasks
    context = {
        "todos": request.user.todos.all().order_by("-created_at"),
        "fullname": request.user.get_full_name() or request.user.username,
    }

    return render(request, "tasks.html", context)
ログイン後にコピー

上記のコードにはすでに変更が加えられており、最初に最新の Todo で並べ替えるようになっています。長いリストが予想されるので、新しい項目を一番下に追加して無限スクロールと混ぜるのは意味がありません。新しい項目はリストの真ん中に混ぜられてしまいます。

ここで、通常の GET リクエストと HTMX リクエストを区別する必要があります。これに対して、todo のリストと部分的なテンプレートのみを返します。 django-htmx というライブラリがあり、これは request.htmx などの属性とすべての hx-* 属性の値を使用してリクエスト パラメーターを拡張するため、非常に便利ですが、現時点ではやりすぎです。ここまでで HTMX ヘッダーを確認し、Django のページネーターを使用してページングを処理しましょう。

# core/views.py

... previous code

PAGE_SIZE = 20

...previous code

@require_http_methods(["GET", "POST"])
@login_required
def tasks(request):
    if request.method == "POST":
        return _create_todo(request)

    page_number = int(request.GET.get("page", 1))

    all_todos = request.user.todos.all().order_by("-created_at")
    paginator = Paginator(all_todos, PAGE_SIZE)
    curr_page = paginator.get_page(page_number)

    context = {
        "todos": curr_page.object_list,
        "fullname": request.user.get_full_name() or request.user.username,
        "next_page_number": page_number + 1 if curr_page.has_next() else None,
    }

    template_name = "tasks.html"

    if "HX-Request" in request.headers:
        template_name += "#todo-items-partial"

    return render(request, template_name, context)
ログイン後にコピー

最初にページパラメータを確認し、存在しない場合は 1 に設定します。

リクエスト内の HX-Request ヘッダーをチェックします。これにより、受信リクエストが HTMX からのものであるかどうかがわかり、それに応じて部分テンプレートまたは完全なテンプレートを返すことができます。

このコードには確かにいくつかのテストが必要ですが、その前に試してみましょう。最後のページに到達するまで、ページがスクロールされるときにネットワーク ツールがどのようにリクエストを発行するかを見てください。アニメーション化された「読み込み中」アイコンが一瞬表示されることもあります。より長く表示できるように、ネットワーク速度を 4g に抑制しました。

Creating a To-Do app with HTMX and Django, part infinite scroll

テストの追加

最後に、ページネーションが意図したとおりに機能することを確認するテストを追加します

<ul>



<p>Soon we will get back to the template to add the hx-get ... hx-trigger="revealed" bit that performs the infinite scroll, but first let's just change the view to return several items instead of  one on the toggle and create operations:<br>
</p>

<pre class="brush:php;toolbar:false">... previous code 

def _create_todo(request):
    title = request.POST.get("title")
    if not title:
        raise ValueError("Title is required")

    todo = Todo.objects.create(title=title, user=request.user)

    return render(
        request,
        "tasks.html#todo-items-partial", # <-- CHANGED
        {"todos": [todo]}, # <-- CHANGED
        status=HTTPStatus.CREATED,
    )

... previous code 


@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-items-partial",  # <-- CHANGED
        {
            "todos": [todo], # <-- CHANGED
        },
    )

ログイン後にコピー

これで終わりです!これは、これまで HTMX で体験した中で最も楽しかったです。この投稿の完全なコードはここにあります。

次の投稿では、AlpineJS を使用したクライアント状態管理を追加するか、「期限」機能を追加することを検討しています。また会いましょう!

以上がHTMX と Django を使用した To-Do アプリの作成 (一部無限スクロール)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート