본문 바로가기

Web Development/Django

[Django] app폴더 서브폴더 안으로 이동시키기

728x90

1. app 폴더 서브폴더 안으로 이동

1) app 초기 생성부터, 서브 폴더 안에서 시작하고 싶은 경우

아래 명령문과 같이 서브 폴더 내 만들고자 하는 앱 이름의 폴더를 생성한뒤, 

python manage.py startapp 명령어로 앱을 서브 폴더 내 앱 폴더의 위치에서 생성하겠다는 선언을 한다. 

 

mkdir <서브 폴더명>/<앱 이름>
python manage.py startapp <앱 이름>  <서브 폴더명>/<앱 이름>

 

예시 (myapp이라는 앱을 apps 폴더 내 생성)

mkdir apps/myapp
python manage.py startapp myapp  apps/myapp

 

2) 이미 app폴더가 있으며, 이동만 시키고 싶은 경우

이 경우에는 app 폴더를 서브 폴더 안으로 이동시킨 후, 다음 단계를 진행한다. 

 

2. 앱 폴더 내 apps.py의 name을 아래와 같이 <서브 폴더명>.<앱 이름>으로 수정한다.

class AppConfig(AppConfig):
    # optional, add default auto field
    default_auto_field = 'django.db.models.BigAutoField'
    # set location of app using sub dir
    name = '<서브 폴더명>.<앱 이름>'

 

예시

class MyappConfig(AppConfig):
    # optional, add default auto field
    default_auto_field = 'django.db.models.BigAutoField'
    # set location of app using sub dir
    name = 'apps.myapp'

3. settings.py 파일의 INSTALLED_APPS를 아래와 같이 <서브 폴더명>.<앱 이름>으로 생성/수정한다. 

INSTALLED_APPS = (
    ...
    '<서브 폴더명>.<앱 이름>',
)

 

예시

INSTALLED_APPS = (
    ...
    'apps.myapp',
)

4. urls.py 파일의 urlpatterns를 아래와 같이 <서브 폴더명>.<앱 이름>.urls로 수정한다

urlpatterns = [
    ...
    path('<url 주소>/', include('<서브 폴더명>.<앱 이름>.urls')),
    ...
]

 

예시

urlpatterns = patterns('', 
  url(r'^myapp', include('apps.myapp.urls')),
  ...
)

5. migration 경로 수정 (migration이 필요한 경우에만) 

makemigrations <앱 이름> --pythonpath='<서브 폴더명>'

 

예시

makemigrations myapp --pythonpath='apps'

Reference

 

django apps in subfolder

Given a sub-directory named "apps" for all django applications, the following steps are used to setup the sub-directory and create apps. 1 create app sub folder - "apps" mkdir apps touch apps/__init__.py 2 add app to sub folder: mkdir apps/myapp python man

makandracards.com

반응형