장고 프로젝트 기본 세팅
1. 프로젝트 디렉토리 생성 + 가상환경 세팅
mkdir mysite # 프로젝트 디렉토리 생성 후 이동
cd mysite
-m venv venv # 가상환경 생성. -m venv {가상환경 이름}
source ./venv/bin/activate # 가상환경 활성화. 나갈 때에는 deactivate
pip install django # 장고 설치
2. 장고 프로젝트 생성 및 앱 생성
django-admin startproject myproject . # myproject 부분이 프로젝트명 / .이 있어야 현재 디렉토리에 생성
# 이 시점에 venv폴더와 myproject 폴더가 병렬이어야 함
cd myproject
python manage.py startapp main # main 앱 생성
python manage.py startapp blog # blog 앱 생성
# settings.py
ALLOWED_HOSTS = ["*"]
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main', # 생성한 앱 추가
'blog', # 생성한 앱 추가
]
# urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('blog/', include('blog.urls')),
]
'''
# 단일앱인 경우 이렇게 작성해도 괜춘
from main.views import about, board, contact, index
urlpatterns = [
path('admin/', admin.site.urls),
path('', index),
path('about/', about),
path('contact/',contact),
path('board/', board),
]
'''
3. 앱 별로 url과 view 세팅
# blog 앱으로 예시
# 앱마다 urls.py 파일 생성
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_list, name="blog_list"),
path('<int:id>/', views.blog_detail, name="blog_list"),
]
# views.py에서 간단히 확인. html 템플릿 렌더는 밑에서 설명
from django.http import HttpResponse
def blog_list(request):
return HttpResponse("<h1>blog_list 화면입니다.</h1>")
def blog_detail(request, id):
return HttpResponse("<h1>blog_detail id : {id}</h1>")
4. 세팅 완료 후 서버 띄워 확인하기
python manage.py migrate
python manage.py runserver
장고 모놀리식 개발 세팅
템플릿을 앱 별로 관리할 것인지 중앙에서 관리할 것인지 결정 필요.
Case 1. 앱 별로 템플릿 관리할 때
''' 예시 폴더 트리
📦 Root
┣ 📂myproject
┣ 📂main
┃ ┗ 📂templates
┃ ┗ 📂main
┃ ┗ 📜index.html
┗ 📂blog
┗ 📂templates
┗ 📂blog
┣ 📜blog_list.html
┗ 📜blog_detail.html
'''
Case 2. 한 폴더에서 템플릿 관리할 때
# 1. 프로젝트 루트 경로에 templates 폴더 생성
# 2. templates 폴더 하위에 앱 별로 폴더 만들어 html 관리
''' 예시 폴더 트리
📦 Root
┣ 📂myproject
┣ 📂main
┣ 📂blog
┗ 📂templates
┣ 📂main
┃ ┗ 📜index.html
┗ 📂blog
┣ 📜blog_list.html
┗ 📜blog_detail.html
'''
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / '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',
],
},
},
]
# views.py
def blog_detail(request, id):
context = {"id":id} #
return render(request, "blog/blog_detail.html", context)
부트스트랩 이용할 때 static 경로 설정
# root폴더 밑에 static 폴더 생성하고 그 밑에 bootstrap asset 이동
# settings.py
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / "static"]
템플릿 html 분리해서 관리
예시 요구사항)
- 공통된 html양식을 base.html에
- header, footer html 분리해서 따로 관리
- 각 페이지 html 따로 관리
# base/base.html
{% load static %}
<!doctype html>
<html lang="zxx">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>sample</title>
<link rel="icon" href="{% static 'img/favicon.png' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
</head>
<body>
{% block header %}
{% include "base/header.html" %}
{% endblock %}
{% block contents %}
{% endblock %}
{% block footer %}
{% include "base/footer.html" %}
{% endblock %}
</body>
</html>
# base/header.html
{% load static %}
<header>
<div class="container">
<h1>
<a class="navbar-brand" href="/"> <img src="{% static 'img/logo.png' %}" alt="logo"> </a>
</h1>
</div>
</header>
# blog/blog_list.html
{% extends "base/base.html" %}
{% block contents %}
{% load static %}
... html 내용
{% endblock %}
** vscode에서 django 템플릿 작업 시 html 자동완성이 안먹힌다. 아래 링크 참조해서 세팅하면 간편해짐.
'공부 > Django' 카테고리의 다른 글
Lightsail로 Django DRF https 배포하기 - 1. 서버세팅 (1) | 2024.04.25 |
---|---|
CBV로 블로그 CRUD 예제 (1) | 2024.02.27 |
CBV로 Django auth 구현 (0) | 2024.02.27 |
forms.py 이용해 웹 페이지에서 CRUD하기 (0) | 2024.02.26 |
장고 Model 세팅 + Q검색 (0) | 2024.02.25 |