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

首頁 后端開發(fā) Python教程 使用 HTMX 和 Django 創(chuàng)建待辦事項應用程序,部分無限滾動

使用 HTMX 和 Django 創(chuàng)建待辦事項應用程序,部分無限滾動

Jan 06, 2025 pm 12:41 PM

這是該系列的第 7 部分,我將在其中記錄我使用 Django 學習 HTMX 的過程,其中我們將按照 HTMX 的文檔來實現(xiàn)待辦事項的無限滾動功能。

如果您想查看該系列的其余部分,請查看 dev.to/rodbv 以獲得完整列表。

更新部分模板以加載多個項目

當我們實現(xiàn)無限滾動時,我們將必須返回幾個待辦事項(項目的下一個“頁面”)并將它們加載到我們當前擁有的部分模板中。這意味著稍微改變我們的部分模板的組成方式;目前的設置如下圖所示,其中部分模板負責渲染單個待辦事項:

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

我們想要反轉順序,使部分圍繞 for 循環(huán):

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

讓我們在模板 core/templates/index.html 中執(zhí)行交換:

<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
        },
    )

檢查內容的測試仍然通過,并且頁面看起來相同,因此我們很好地實現(xiàn)無限滾動本身。

實現(xiàn)無限滾動

在模板上,我們需要向 /tasks 設置一個 hx-get 請求,其中 hx-trigger="revealed" ,這意味著只有當元素即將進入屏幕上可見時才會觸發(fā) GET 請求;這意味著我們希望將其設置在列表中最后一個元素之后,并且我們還需要指示要加載哪個“頁面”數(shù)據(jù)。在我們的例子中,我們將一次顯示 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)

上面的代碼已經做了改動,就是按照最新的待辦事項優(yōu)先排序;既然我們期望有一個很長的列表,那么在底部添加新項目并將其與無限滾動混合是沒有意義的 - 新項目最終將混合在列表的中間。

我們現(xiàn)在需要區(qū)分常規(guī) GET 請求和 HTMX 請求,為此我們將僅返回待辦事項列表和部分模板。有一個名為 django-htmx 的庫,它非常方便,因為它使用 request.htmx 等屬性和所有 hx-* 屬性的值擴展了請求參數(shù),但目前這有點過分了;現(xiàn)在讓我們檢查 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)

我們做的第一件事是檢查頁面參數(shù),如果不存在則將其設置為 1。

我們檢查請求中的 HX-Request 標頭,這將告知我們傳入的請求是否來自 HTMX,并讓我們相應地返回部分模板或完整模板。

這段代碼肯定需要一些測試,但在此之前讓我們先嘗試一下??匆幌戮W絡工具,當頁面滾動時如何觸發(fā)請求,直到到達最后一頁。您還可以看到動畫“正在加載”圖標短暫顯示;我已將網絡速度限制為 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
        },
    )

現(xiàn)在就這樣了!這是迄今為止我使用 HTMX 遇到的最有趣的事情。這篇文章的完整代碼在這里。

對于下一篇文章,我正在考慮使用 AlpineJS 添加一些客戶端狀態(tài)管理,或者添加“截止日期”功能。再見!

以上是使用 HTMX 和 Django 創(chuàng)建待辦事項應用程序,部分無限滾動的詳細內容。更多信息請關注PHP中文網其他相關文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

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

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

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

多態(tài)是Python面向對象編程中的核心概念,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪制程序中統(tǒng)一調用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

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

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

如何在Python中產生隨機字符串? 如何在Python中產生隨機字符串? Jun 21, 2025 am 01:02 AM

要生成隨機字符串,可以使用Python的random和string模塊組合。具體步驟為:1.導入random和string模塊;2.定義字符池如string.ascii_letters和string.digits;3.設定所需長度;4.調用random.choices()生成字符串。例如代碼包括importrandom與importstring、設置length=10、characters=string.ascii_letters string.digits并執(zhí)行''.join(random.c

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中通過@classmethod裝飾器定義的方法,其第一個參數(shù)為類本身(cls),用于訪問或修改類狀態(tài)。它可通過類或實例調用,影響的是整個類而非特定實例;例如在Person類中,show_count()方法統(tǒng)計創(chuàng)建的對象數(shù)量;定義類方法時需使用@classmethod裝飾器并將首參命名為cls,如change_var(new_value)方法可修改類變量;類方法與實例方法(self參數(shù))、靜態(tài)方法(無自動參數(shù))不同,適用于工廠方法、替代構造函數(shù)及管理類變量等場景;常見用途包括從

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

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

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

參數(shù)(parameters)是定義函數(shù)時的占位符,而傳參(arguments)是調用時傳入的具體值。1.位置參數(shù)需按順序傳遞,順序錯誤會導致結果錯誤;2.關鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認參數(shù)值在定義時賦值,避免重復代碼,但應避免使用可變對象作為默認值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用于通用接口或裝飾器,但應謹慎使用以保持可讀性。

See all articles