[Django] 구조 이해하기

2 minute read


DJANGO WEB DEVELOPMENT

2. DJANGO 구조 이해하기


django 프로젝트 생성

# 가상환경 안에 들어간 후 (django-admin startproject [project_name])
django-admin startproject costaurant

# 생성된 나의 프로젝트 폴더에 들어가기
cd costaurant

# 해당 폴더에서 vscode 실행
code .

# 서버 실행
python manage.py runserver

django 프로젝트 구조

  • project root - 프로젝트 최상위의 디렉토리 (ex)~/first_django/costaurant)
  • manage.py - 프로젝트 관리를 위한 명령 유틸리티
    • django 앱을 만들기, 데이터베이스 관련 기능을 수행, 개발 서버를 실행 등
  • project app(django root) - project root 안에 있는 프로젝트명의 directory (ex)~/first_django/costaurant/costaurant)
  • __ init __.py - python 패키지로 인식하게끔 하는 파일(하위호환)
  • settings.py - django 프로젝트의 여러 가지 설정을 담고 있는 파일
  • urls.py - django 프로젝트로 들어온 url을 보고 알맞은 로직(View)으로 연결해주는 역할을 하는 파일, 일종의 목차
  • wsgi.py - WebServer Gateway Interface의 약자로 파이썬에서 웹 통신을 하기 위한 일종의 약속

django app

  • django project - 웹서비스 전체
  • django app - 기능을 나타내는 단위
# 앱 설치 - project app directory에 가서 (python manage.py startapp {app_name}
python manage.py startapp foods

# settings.py에 app_name 추가
Installed_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'foods'
]
  • admin.py - django 관리자와 연동하기 위해 필요한 설정 파일
  • apps.py - 해당 앱에 대한 설정 넣는 파일
  • tests.py - 프로젝트의 테스트 코드를 작성하는 파일
  • models.py - 해당 앱에서 사용할 데이터 모델을 정의(즉, 데이터베이스 연동과 연관된 파일)
  • views.py - 서버에 요청이 들어왔을 때, 어떻게 처리하는지 메인 로직이 들어가는 파일
  • migrations - 데이터베이스의 변경 사항에 대한 history 누적

url 만들기

  • domain/foods/index 링크 만들기
  • URL 작성시 참고사항(현재 naver.com/cloth 에 있다고 했을 때)
    • 앞에 슬래시/가 있을 경우 도멘으로부터의 경로
      • <a href=”/watch/”>이동하기</a> ➡️ naver.com/watch
    • 앞에 슬래시(/)가 없는 경우 현재 URL부터의 경로
      • <a href=”pants/”>이동하기</a> ➡️ naver.com/cloth/pants
# 'costaurant/' directory의 settings.py 파일
from django.contrib import admin
from django.urls import path,include

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

# 'foods/' directory에 urls.py 만들기
# foods/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index)
]

# 'foods/' directory의 views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse('<h2>Hello, Django!</h2>')

# 사이트 확인
# http://localhost:8000/foods/index/

render

# foods directory 안에 template directory, 그리고 그 안에 또 foods 라는 directory 생성
# foods/template/foods directory에 index.html 파일 생성 후 html 코드를 기입

# 'foods/' directory의 views.py 파일
def index(request):
    return render(request, 'foods/index.html')

# 사이트 확인
# http://127.0.0.1:8000/foods/index/
  • render 함수는 인자로 주어진 템플릿을 사전형(dict) 인자인 context와 결합해서 렌더링을 거친 다음 HttpResponse 객체로 반환하는 함수
  • render(request, template_name, context=None, context_type=None, status=None, using=None)
  • request에는 데이터를 요청한 요청 객체를 넘겨줌, 앞에서 함수형 index의 인자로 들어온 request를 render에 그대로 사용
    • context - 템플릿에 추가할 값들이 들어 있는 사전형 인자로 기본값은 아무것도 없는 None
    • content_type - 결과로 만들어 내는 문서의 유형을 말하며 기본값은 ‘text/html’
    • status - 상태 코드(Status Code) 값이며 기본값은 200
    • using - 템플릿을 렌더하는 템플릿 엔진을 지정할 수 있는 인자