搜尋
首頁後端開發Python教學使用 HTMX 和 Django 建立待辦事項應用程序,部分無限滾動

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

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

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

當我們實作無限滾動時,我們將必須傳回幾個待辦事項(專案的下一個「頁面」)並將它們載入到我們目前擁有的部分範本中。這意味著稍微改變我們的部分範本的組成方式;目前的設定如下圖所示,其中部分範本負責渲染單一待辦事項:

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 中執行交換:


    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:

... 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", # 



<p>檢查內容的測試仍然通過,而且頁面看起來相同,因此我們很好地實現無限滾動本身。 </p>

<h2>
  
  
  實現無限滾動
</h2>

<p>在模板上,我們需要向/tasks 設定一個hx-get 請求,其中hx-trigger="revealed" ,這意味著只有當元素即將進入螢幕上可見時才會觸發GET 請求;這意味著我們希望將其設定在清單中最後一個元素之後,並且我們還需要指示要載入哪個「頁面」資料。在我們的例子中,我們將一次顯示 20 個項目。 </p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173613850692024.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Creating a To-Do app with HTMX and Django, part infinite scroll"></p>

<p>讓我們相應地更改模板:<br>
</p>

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

    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

    The directive hx-swap:outerHTML indicates that we will replace the outerHTML of this element with the set of

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

    We can now move to the views file.

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

    @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)
    

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

    我們現在需要區分常規 GET 請求和 HTMX 請求,為此我們將只傳回待辦事項清單和部分範本。有一個名為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

    添加測試

    最後,我們可以新增一個測驗來確保分頁能如預期運作

    
    

      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:

    ... 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", # 
    
    
    
    <p>現在就這樣了!這是迄今為止我使用 HTMX 遇到的最有趣的事情。這篇文章的完整程式碼在這裡。 </p>
    
    <p>對於下一篇文章,我正在考慮使用 AlpineJS 新增一些客戶端狀態管理,或新增「截止日期」功能。再見! </p>
    
    
              
    
                
            

以上是使用 HTMX 和 Django 建立待辦事項應用程序,部分無限滾動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的內存足跡與python數組的內存足跡相比如何?列表的內存足跡與python數組的內存足跡相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

部署可執行的Python腳本時,如何處理特定環境的配置?部署可執行的Python腳本時,如何處理特定環境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境