Skip to content

Instantly share code, notes, and snippets.

@parkjoohwan
Last active December 30, 2023 04:34
Show Gist options
  • Save parkjoohwan/2c986c6c5f30375c88f06527442cd26b to your computer and use it in GitHub Desktop.
Save parkjoohwan/2c986c6c5f30375c88f06527442cd26b to your computer and use it in GitHub Desktop.
django 프로젝트 구조 요약

장고 프로젝트 기본 구조

django-project 
    +-- django-project
        +-- static (모든 앱 공통 css, js, img 등 static 리소스 디렉토리)
            +-- [common css directory]
            +-- [common js directory]
            +-- [common img directory]
        +--templates (모든 앱 공통 template(layout) 관리 디렉토리)
            +-- [common template(layout) directory]
        -- __init__.py
        -- settings.py
        -- urls.py
        -- wsgi.py
    +-- app1
        +-- migrations (model.py 기반 테이블 관리용)
            -- __init__.py
        +-- templates (app1의 template 관리 디렉토리)
            -- [app1 template directory] 
        -- __init__.py
        -- admin.py
        -- apps.py
        -- models.py
        -- tests.py
        -- urls.py
        -- views.py
    +-- app2
        +-- migrations (model.py 기반 테이블 관리용)
            -- __init__.py
        +-- templates (app2의 template 관리 디렉토리)
            -- [app2 template directory] 
        -- __init__.py
        -- admin.py
        -- apps.py
        -- models.py
        -- tests.py
        -- urls.py
        -- views.py
    - manage.py

Django 는 MVC(Model-View-Controller) 패턴과 대응되는 MTV(Model - Template - View) 패턴의 프레임워크입니다.

다른 언어와 비교하자면 node .js과 가장 유사합니다.

Django를 설치하고 django-admin.py startproject [프로젝트 명] 명령을 실행하면

[프로젝트 명]
    +-- [프로젝트 명]
        -- __init__.py
        -- settings.py
        -- urls.py
        -- wsgi.py
    -- manage.py

위와같은 기본 프로젝트 폴더가 생성됩니다.

  • settings.py settings.py 파일은 django프로젝트의 config를 설정하는 파일입니다. 데이터베이스, 서버 실행시 포함될 module(app), 인증 등 기본 설정들을 할 수 있습니다.

  • urls.py urls.py 파일은 url에 어떤 페이지를 세팅할 것인지 관리하는 파일입니다. route를 담당하는 파일이라고 생각하시면됩니다.

  • wsgi.py wsgi.py 파일은 Web Server Gateway Interface의 약자로 서버와 응용 프로그램이 통신하는 인터페이스로 클라이언트로부터 요청을 수신하고이를 애플리케이션으로 전달한 다음 애플리케이션이 리턴 한 응답을 클라이언트로 보내는 역할을 합니다.

  • manage.py manage.py은 장고 웹 서버를 실행하고 사이트를 관리할 수 있도록 도와주는 파일입니다. python manage.py를 실행하면 어떤 기능이 있는지 확인할 수 있습니다.

#python .\manage.py

Type 'manage.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

django 프레임 워크의 장점은 하나의 사이트를 개발하게되면, 관리자 페이지 하나를 쉽게 만들 수 있게 된다는 점입니다.

프로젝트 내에서 python manage.py startapp [앱 명]을 실행하면

[앱 명]
 +-- migrations 
    -- __init__.py
    -- admin.py
    -- apps.py
    -- models.py
    -- tests.py
    -- urls.py
    -- views.py

위와같은 디렉토리와 파일이 생성되는데, 이 admin.py 파일에서 몇줄의 코드 작성으로, 특정 앱의 관리자 페이지를 만들 수 있고, 삽입, 수정, 삭제 등이 가능하게됩니다.

또, tests.py 파일에서 기능, 단위 테스트를 간단하게 구현 할 수 있습니다. 이는 python에서 기본적으로 지원하는 pytest 모듈과 unittest모듈을 선택해서 사용 할 수 있습니다.

아래와같이 testapi라는 앱을 만들고, 간단한 텍스트를 return하는 api를 만든 뒤, 아래와같이 tests.py를 구현해서 서버를 실행하지 않고도 개발한 기능이 정상적으로 작동하는지 확인할 수 있습니다.

# /testapi/tests.py

from django.test import TestCase
from django.urls import resolve

from .views import testapi

class ApiTest(TestCase):
    def test_testapi_return_values(self):
        response = self.client.get('/apis/testapi/') # /apis/testapi/ 경로 호출 후, response 값 저장하기
        #print(response.content.decode())
        self.assertIn('test api 테스트', response.content.decode())    # 테스트 값
        
    def test_otherapi_return_values(self):
        response = self.client.get('/apis/otherapi/') # /apis/otherapi/ 경로 호출 후, response 값 저장하기
        self.assertIn('other api 테스트', response.content.decode())    # 테스트 값

가장 맨 위에 적힌 django 프로젝트의 기본 구조를 보면 startproject [프로젝트], startapp [앱] 을 실행했을때에 생성되지 않는 static, templates 등의 디렉토리가 있습니다. 이는 django 기본 setting.py 파일을 확인하면 기본적으로 설정되어있는 css, js, images 들을 저장하는 static 디렉토리와 templates 설정을 확인 할 수 있습니다.

#template 설정

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'MyFirstDjango', 'templates')],
        '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',
            ],
        },
    },
]

#static 설정
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'MyFirstDjango', 'static')
]

startproject를 통해 생성된 디렉토리 내의 template은 일반적으로 웹 사이트의 공통 레이아웃들을 담아두는 폴더로 활용하고, startapp을 통해 생성된 디렉토리 내의 template은 해당 앱만의 고유 레이아웃이나, view 페이지를 담아두는 디렉토리입니다.

예를들면, 가장 간단한 공통 레이아웃은

<!-- base.html -->
{% load static %}

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="{% static 'css/project.css' %}">
    <script type="text/javascript" href="{% static 'js/project.js' %}">

    <title>My First Django</title>
  </head>
  <body>

    {% block content %}
    {% endblock %}

  </body>
</html>

위와 같이 작성됩니다. 만약 이 템플릿 내에 _navbar 같은 다른 공통 template을 사용하고 싶다면 원하는 위치에 {% include 'share/_navbar.html' %}을 적어주면됩니니다.

또 만약 프로젝트의 static 경로에 있는 리소스 파일들을 사용하고 싶다면 맨 위에 {% load static %}을 입력하고 사용할 파일을 지정하면 됩니다.

{% block content %}
    {% endblock %}

이 부분에는 공통 레이아웃 외에, app의 template 경로에 작성되는 html 코드가 삽입되는 부분입니다.

만약 앱에 다음과같이

{% extends 'base.html' %}

{% block content %}
{% include '_navbar.html' %}
<h1>
    first
</h1>
{% endblock %}

코드를 작성하고 서버를 실행하고 페이지를 확인하면

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="[css 경로] ">
    <script type="text/javascript" href="[js 경로]">

    <title>My First Django</title>
  </head>
  <body>
   [_navbar.html]
   <h1>
        first
   </h1>
  </body>
</html>

처럼 나타나게 됩니다.

작성중입니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment