본문 바로가기
개발 그리고../django(파이썬)

장고 앱 시작 단계

by iamgalimto 2022. 12. 14.

App 생성

   

python manage.py startapp board

board App은 아래와 같은 디렉토리/파일 구조를 갖는다.

C:.
│  db.sqlite3
│  manage.py
│
├─board
│  │  admin.py
│  │  apps.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
└─config
    │  asgi.py
    │  settings.py
    │  urls.py
    │  wsgi.py
    │  __init__.py

App 등록 - board/settings.py

INSTALLED_APPS = [
    'board.apps.BoardConfig', # 추가한 App을 등록한다.
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

INDEX 페이지 생성

  board App에 index페이지를 생성한다. 먼저 board/views.py 에 index 요청 처리 함수를 생성한다.

 

board/views.py

from django.shortcuts import render

def index(request):
    context = {
        'title': 'Board list',
        'board_list': [
            {'no':1, 'title': '목록1' },
            {'no':2, 'title': '목록2' },
            {'no':3, 'title': '목록3' },
            {'no':4, 'title': '목록4' },
            {'no':5, 'title': '목록5' }
        ]
    }
    return render(request, 'board/index.html', context)

게시판 테스트를 위해 하드코딩된 리스트를 요청의 응답으로 리턴한다.

render 객체는 템플릿 자원을 렌더링하는 http 응답 객체이다. 

생성한 index 함수의 url 매핑을 위해 mysite/urls.py의 urlpatterns 변수 path를 등록한다.

 

mysite/urls.py

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('board/', include('board.urls')),
    path('admin/', admin.site.urls),
]

App이 증가하면서 url이 많아지는 경우 프로젝트 레벨에서 모든 url을 관리하기 힘들다. include 를 사용하여 각 App내에 위치한 url정의 파일을 등록할 수 있다. App내에 urls.py를 생성하여 다음과 같이 url을 정의한다.

 

board/urls.py

from django.urls import path

from . import views

app_name = 'board'
urlpatterns = [
    path('', views.index, name='index')
]

 

html 리소스는 Django template기능을 사용하여 출력한다. 

DjangoTemplates  templates 디렉토리 내에 html 리소스를 검색한다. 아래와 같이 디렉토리 생성 후 해당 위치에 index.html 파일을 위치한다.

 

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        ...
    },
]

 

board/templates/board/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>{{ title }}</h2>

{% if board_list %}
    <ul>
        {% for data in board_list %}
        <li>{{ data.no }} : {{ data.title }}</li>
        {% endfor %}
    </ul>
{% else %}
    <h2>no board list</h2>
{% endif %}
</body>
</html>

서버에서 리턴한 응답데이터는 DTL(Django template language)를 사용하여 접근할 수 있다. DTL의 자세한 사용법은 아래 링크를 참조한다.

docs.djangoproject.com/en/3.1/topics/templates/

 

Templates | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

서버 기동 후 http://127.0.0.1:8000/board/ 로 접속한다.

 

 

참조 : https://youngwonhan-family.tistory.com/35

 

1. 게시판 만들기 - Django 3.x 설치 및 핵심개념 파악

Django(장고)란 ? Django는 python 베이스에 free, open-source 웹프레임워크이다. Full-stack Framework 로 인증(auth), 관리자(admin), 세션(session), 메세지(messages) 등 웹에 필요한 필수기능과 다양한 미들웨어를 제

youngwonhan-family.tistory.com

 

'개발 그리고.. > django(파이썬)' 카테고리의 다른 글

requirements.txt활용한 django개발환경 유지  (0) 2022.12.07
.gitignore 파일  (0) 2022.10.28