Django 및 HTMX를 사용하여 To-Do 앱 만들기 - 파트 프런트엔드 만들기 및 HTMX 추가
시리즈 3부에 오신 것을 환영합니다! 이 기사 시리즈에서는 백엔드에 Django를 사용하여 제가 직접 학습한 HTMX를 기록하고 있습니다.
이제 막 시리즈를 시작하셨다면 1부와 2부를 먼저 확인해 보시는 것도 좋을 것 같습니다.
템플릿 및 보기 만들기
기본 템플릿과 데이터베이스에 있는 할일 목록을 나열하는 인덱스 뷰를 가리키는 인덱스 템플릿을 만드는 것부터 시작하겠습니다. Tailwind CSS의 확장인 DaisyUI를 사용하여 Todos를 보기 좋게 만들어 보겠습니다.
뷰가 설정된 후 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에서 루프를 반복합니다.
이제 항목을 켜고 끄는 기능을 테스트할 수 있습니다.
클라이언트 측 작업을 수행하는 것처럼 보이지만 브라우저에서 네트워크 도구를 검사하면 PUT 요청을 전달하고 부분 HTML을 반환하는 방법을 알 수 있습니다.
PUT 요청
응답
이제 우리 앱은 HTMX를 지원합니다! 여기에서 최종 코드를 확인할 수 있습니다. 4부에서는 작업을 추가하고 삭제하는 기능을 추가하겠습니다.
위 내용은 Django 및 HTMX를 사용하여 To-Do 앱 만들기 - 파트 프런트엔드 만들기 및 HTMX 추가의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

Python은 게임 및 GUI 개발에서 탁월합니다. 1) 게임 개발은 Pygame을 사용하여 드로잉, 오디오 및 기타 기능을 제공하며 2D 게임을 만드는 데 적합합니다. 2) GUI 개발은 Tkinter 또는 PYQT를 선택할 수 있습니다. Tkinter는 간단하고 사용하기 쉽고 PYQT는 풍부한 기능을 가지고 있으며 전문 개발에 적합합니다.

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.
