인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

bigseoul님의 프로필 이미지

작성한 질문수

파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 (장고 4.2 기준)

11-02 myproj 프로젝트 생성 및 초기 설정 #2 - Toast 이벤트 구성, django-crispy-forms, django-components 및 modal-form 컴포넌트

Django-Components의 0.128 세팅

작성

·

144

0

최신 버전에선 강의의 설정을 적용할 수 없습니다.

아래의 것을 참고하세요.

(강사님 이렇게 해도 되긋죠? 구조 제대로 이해 못한채 chatgpt에게 물으면서 했네요 ㅎㅎ; 강의 유지보수 하시기 힘드시겠어요. )

django_components 0.128 설정

1. 폴더명 및 트리구조 변경.

myproj/

├── core/

│ ├── init.py

│ ├── apps.py

│ ├── src_django_components/ * 폴더명 변경. 하이픈 인식 못함.

│ │ ├── init.py

│ │ ├── modal_form.py * 상위로 이동

│ │ ├── modal_form/

│ │ │ ├── modal_form.html

│ │ │ ├── modal_form.css

│ │ │ ├── modal_form.js

├── mysite/

│ ├── settings.py

│ ├── urls.py

├── manage.py

 

2. settings.py

INSTALLED_APPS = [

...,

'django_components',

]

MIDDLEWARE = [

...,

"django_components.middleware.ComponentDependencyMiddleware",

]

STATICFILES_FINDERS = [

"django.contrib.staticfiles.finders.FileSystemFinder",

"django.contrib.staticfiles.finders.AppDirectoriesFinder",

"django_components.finders.ComponentsFileSystemFinder",

]

TEMPLATES = [

...,

"DIRS": [BASE_DIR / "core" / "src_django_components"],

],

"OPTIONS": {

"context_processors": [

"django.template.context_processors.debug",

"django.template.context_processors.request",

"django.contrib.auth.context_processors.auth",

"django.contrib.messages.context_processors.messages",

],

"builtins": [

"django_components.templatetags.component_tags", # 추가된 부분

],

...,

STATICFILES_DIRS = [BASE_DIR / "core" /"src_django_components"]

COMPONENTS = ComponentsSettings(

dirs=[

Path(BASE_DIR) / "core" / "src_django_components",

]

)

3. core/apps.py

-modal_form 등록

from django.apps import AppConfig

from django_components import component

class CoreConfig(AppConfig):

default_auto_field = "django.db.models.BigAutoField"

name = "core"

def ready(self):

from .src_django_components.modal_form import ModalForm

component.registry.register("modal_form", ModalForm) # 설명: ModalForm 클래스를 modal_form 이름으로 등록합니다.

 

답변 3

0

이진석님의 프로필 이미지
이진석
지식공유자

안녕하세요. 어느덧 django-components 버전도 0.129 버전이 되었네요.

강의의 장고 프로젝트에 django-components 0.129 버전 대응 방법을 아래 링크에 정리해봤습니다.
https://ai.pyhub.kr/django/components/django-components/setup

아래 커밋을 통해서도 동작을 확인했으니, 확인해보시고 댓글 부탁드립니다. :-)

https://github.com/pyhub-kr/course-django-complete-guide-v3/commit/c0d965ac1a1df9a33986b70ff6d8a65e8b699fc9

늦어서 죄송합니다.

bigseoul님의 프로필 이미지
bigseoul
질문자

잘 정리해 주셔서 고맙습니다. 동작 확인했습니다. 다만,

 

{% load component_tags %}

  • 신규 설치나 수정 버전에도 위 태그가 필요해요. 부모 템플릿에서 제거해도 된다고 하셨는데, 애러 뜨네요. 이거 넣으면 신규나 업그레이드 모두 잘 작동해요.

 

업그레이드 버전 mysite/settings.py에서

  • BASE_DIR / "mysite" / "templates"은 필요한가요? mysite에는 templates가 없기도 하고요.

     

 

이진석님의 프로필 이미지
이진석
지식공유자

옙. 말씀하신 대로 커스텀 템플릿 태그를 사용하기 위해서는 load 가 필요합니다. 혹은 settings.TEMPLATES 설정에 builtins 설정으로 기본 로딩할 템플릿태그들을 지정하실 수도 있습니다.

그리고 튜토리얼 문서의 mysite/templates 경로는 django-components 설정과는 무관한 설정입니다. 해당 경로에 템플릿 파일이 없다면 무시하셔도 되는 설정입니다. :-)

확인해주셔서 감사드립니다. :-)

0

bigseoul님의 프로필 이미지
bigseoul
질문자

강사님이 최신 django-components 버전을 반영한 수정본이 곧 공개될 것 같습니다.

현 시점에서 작동하는 settings.py 변경점을 기록 삼아 공유해볼게요.

import sys
from pathlib import Path

from django_components import ComponentsSettings #변경
from environ import Env


INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles", #변경
    "django_components",  #변경
    "crispy_forms",
    "crispy_bootstrap5",
    "django_extensions",
    "django_htmx",
    "template_partials",
    "core",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_htmx.middleware.HtmxMiddleware",
    "django_components.middleware.ComponentDependencyMiddleware", #변경
]

if DEBUG:
    MIDDLEWARE.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware")

STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "django_components.finders.ComponentsFileSystemFinder", # 변경
]


TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "core" / "src_django_components"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
            "builtins": [
                "django_components.templatetags.component_tags",
            ], #변경
        },
    },
]


STATIC_ROOT = BASE_DIR / "staticfiles" #변경

# ✅ STATICFILES_DIRS 최적화 (불필요한 경로 제거)
STATICFILES_DIRS = []  # 변경: 필요하면 프로젝트 공통 정적 파일 폴더만 추가

# django-components 설정
COMPONENTS = ComponentsSettings(
    dirs=[BASE_DIR / "core" / "src_django_components"],
)

🔥 설정 적용 후 해야 할 작업, staticfiles에 저장된 중복 파일 제거.

1⃣ 기존 정적 파일 삭제

rm -rf staticfiles/*

2⃣ 새로운 collectstatic 실행

python manage.py collectstatic --noinput

3⃣ 중복 파일 여부 확인(js, html, css )

find staticfiles -name "modal_form.js"

 

이진석님의 프로필 이미지
이진석
지식공유자

경험을 공유해주셔서 너무나 감사드립니다. 제게도 큰 도움 되고 있습니다. 👍

그런데, django-components 매뉴얼을 다 보고, 내용을 제대로 정리해볼려니 예상보다 시간이 꽤 걸리고 네요. 잘 정리해서 다음 주 주중에 꼭 공유해드릴 수 있도록 하겠습니다. :-)

0

이진석님의 프로필 이미지
이진석
지식공유자

와우~!!! 경험 공유 감사드립니다!! 👍👍👍
다른 분들께도 큰 도움이 되실 듯 합니다.

저도 살펴보고, 최신버전에도 적용할 수 있도록 정리해서 강의에도 반영해보겠습니다.

다시 한 번 더 감사드립니다~!!!

bigseoul님의 프로필 이미지
bigseoul
질문자

"django.contrib.staticfiles"도 INSTALLED_APPS에 필요하네요. 다만.

python manage.py collectstatic 명령을 해보니.

Found another file with the destination path 'modal_form/modal_form.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.

Found another file with the destination path 'modal_form/modal_form.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
라는 메시지가 나옵니다.

static 경로를 바꾸라는 거 같아요. components에서 python 파일과 html 파일을 정적 서빙 대상에서 제외하기 위해 src_django_components로 바꾼 것과 서로 영향을 받는 것 같아요.

현재
>find . -name "modal_form.js"
./staticfiles/modal_form/modal_form.js

./core/src_django_components/modal_form/modal_form.js
로 파일이 두 개 존재하는 상황입니다. 제 능력으로 수습하기 어렵네요 ㅎㅎ.

강사님의 도움이 필요합니다.

이진석님의 프로필 이미지
이진석
지식공유자

저녁에 정리해보고, 내용 공유해드릴 수 있도록 하겠습니다. :-)

bigseoul님의 프로필 이미지

작성한 질문수

질문하기