백엔드 개발 파이썬 튜토리얼 Django 및 HTMX를 사용하여 To-Do 앱 만들기 - 파트 프런트엔드 만들기 및 HTMX 추가

Django 및 HTMX를 사용하여 To-Do 앱 만들기 - 파트 프런트엔드 만들기 및 HTMX 추가

Jan 06, 2025 am 12:00 AM

시리즈 3부에 오신 것을 환영합니다! 이 기사 시리즈에서는 백엔드에 Django를 사용하여 제가 직접 학습한 HTMX를 기록하고 있습니다.
이제 막 시리즈를 시작하셨다면 1부와 2부를 먼저 확인해 보시는 것도 좋을 것 같습니다.

템플릿 및 보기 만들기

기본 템플릿과 데이터베이스에 있는 할일 목록을 나열하는 인덱스 뷰를 가리키는 인덱스 템플릿을 만드는 것부터 시작하겠습니다. Tailwind CSS의 확장인 DaisyUI를 사용하여 Todos를 보기 좋게 만들어 보겠습니다.

뷰가 설정된 후 HTMX를 추가하기 전의 페이지 모습은 다음과 같습니다.

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)

로그인 후 복사

여기서 몇 가지 흥미로운 점은 색인 경로(홈 페이지)가 작업 URL로 리디렉션되어 보기만 한다는 것입니다. 이를 통해 향후 앱에 대한 일종의 랜딩 페이지를 자유롭게 구현할 수 있습니다.

작업 보기에는 로그인이 필요하며 컨텍스트에서 두 가지 속성, 즉 필요한 경우 사용자 이름에 통합되는 사용자의 전체 이름과 생성 날짜별로 정렬된 할 일 항목을 반환합니다. 미래).

이제 템플릿을 추가해 보겠습니다. 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
]
로그인 후 복사

작업 템플릿에서는 각 할일 항목을 인라인 부분 템플릿으로 정의합니다. 페이지를 다시 로드하면 시각적인 차이가 없어야 합니다.

<!-- 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 문에서 템플릿 부분을 어떻게 활용할 수 있는지 확인할 수 있습니다. todo-item-partial 이름과 항목 이름과 일치하는 컨텍스트를 참조하여 부분만 반환합니다. Tasks.html에서 루프를 반복합니다.

이제 항목을 켜고 끄는 기능을 테스트할 수 있습니다.

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

클라이언트 측 작업을 수행하는 것처럼 보이지만 브라우저에서 네트워크 도구를 검사하면 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를 지원합니다! 여기에서 최종 코드를 확인할 수 있습니다. 4부에서는 작업을 추가하고 삭제하는 기능을 추가하겠습니다.

위 내용은 Django 및 HTMX를 사용하여 To-Do 앱 만들기 - 파트 프런트엔드 만들기 및 HTMX 추가의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

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 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? 중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? Apr 02, 2025 am 07:15 AM

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? 한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? Apr 01, 2025 pm 11:15 PM

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 Serving_forever ()없이 HTTP 요청을 어떻게 지속적으로 듣습니까? Apr 01, 2025 pm 10:51 PM

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? 10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? Apr 02, 2025 am 07:18 AM

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Apr 02, 2025 am 07:03 AM

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

See all articles