Make Website with django
Model, View, and Template
1. Django 시작하기
- Python 기반 웹 프레임워크
- 장고 플라스크 모두 같은 프레임워크지만 지향하는 바가 다르다. 플라스크는 마이크로(최소한의 기능을 갖고 있음), 반명 장고는 거의 모든것이 내장되있는 스타일
- Django 가상환경 설치하기
pip3 install virtualenv
python3 -m virtualenv <가상환경 이름>
- 가상환경 실행 후 pip install django(반드시 가상 환경 진입 상태인것을 확인하기)
- 가상환경 실행 source venv/bin/activate(맥의 경우)
- pip freeze를 통해 제대로 설치됫나 확인하기
django-admin startproject <project_name>
- manage.py를 통해 프로젝트를 가동할 수 있다.
(webproj 아래에서)
python manage.py runserver
2. django의 구성요소
- settings.py - 전반적인 장고 프로젝트 설정을 담당하고 있는 파일(많이 만지게 됨)
- urls.py - url을 관리하는 곳. 얘도 많이 만지게 됨
- Django Project and App
- 한 Project는 여러 App으로 구성되어있다.
- App - 특정 명령을 수행하는 view와 template의 모음이다.
- Django App 만들기
- 기존에 프로젝트를 시작할떈 프로젝트 루트 디렉터리 안에서 진행했으나 이번에는 프로젝트 아래에서 진행해 줘야함
- webproj라는 프로젝트를 만들었으므로 그 안에서 앱을 생성해 줘야함
django-admin startapp <app_name>
- 앱이 생성됬다.
- Django의 MVT Pattern
3. View로 Request Handling 하기
- homepage/views.py
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello World!")
- webproj/urls.py
from django.contrib import admin
from django.urls import path
from homepage.views import index
urlpatterns = [
path('', index), #127.0.0.1/
path('admin/', admin.site.urls), # 127.0.0.1/admin/
]
- webproj/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'homepage'
]
- 다시 서버를 실행시키고 127.0.0.1로 접속해보면 다음과 같이 페이지가 뜬다.
- 장고 어드민 아이디 패스워드 만들기
python manage.py migrate
장고프로젝트 처음 생성시 admin db가 자동으로 생성되어 먼저 진행해 주어야된다고 한다.
python manage.py createsuperuser
계정을 성공적으로 생성하면 다음처럼 127.0.0.1/admin에서 접속이 가능하다.
3. Template으로 보여줄 화면 구상하기
- render()함수(views.py)
- 먼저 homepage app 디렉터리 아래 template 폴더를 만들고 하위에 index..html을 만들어준다.
- homepage/template/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Python django Example</title>
</head>
<body>
<h1>Title</h1>
<p>blah blah blah</p>
</body>
</html>
- webproj/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'homepage','template')],
'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',
],
},
},
]
- homepage/views.py
from django.shortcuts import render, HttpResponse, render
def index(request):
return render(request, 'index.html', {})
# Create your views here.
- template에 원하는 값 전달해보기
- homepage/views.py
from django.shortcuts import render, HttpResponse, render
def index(request):
number = 10
return render(request, 'index.html', {
"my_num": number
})
# Create your views here.
- template/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Python django Example</title>
</head>
<body>
<h1>Title</h1>
<p>blah blah blah</p>
{{my_num}}
</body>
</html>
- template 필터 적용하기
views.py
from django.shortcuts import render, HttpResponse, render
def index(request):
name = 'TEST'
return render(request, 'index.html', {
"my_name": name
})
# Create your views here.
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Python django Example</title>
</head>
<body>
<h1>Title</h1>
<p>blah blah blah</p>
{{my_name | length}}
</body>
</html>
- template tag
- {% .... %}
for문 예시
views.py
from django.shortcuts import render, HttpResponse, render
def index(request):
name = 'TEST'
test = [1, 2, 3, 4, 5]
return render(request, 'index.html', {
"my_name": name,
'my_list': test,
})
# Create your views here.
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Python django Example</title>
</head>
<body>
<h1>Title</h1>
<p>blah blah blah</p>
{{my_name | length}}
{% for x in my_list %}
<p>{{x}}</p>
{% endfor %}
</body>
</html>
- if tag
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<title>Python django Example</title>
</head>
<body>
<h1>Title</h1>
<p>blah blah blah</p>
{{my_name | length}}
{% for x in my_list %}
{% if x|divisibleby:"2" %}
<p>{{x}}</p>
{% endif %}
{% endfor %}
</body>
</html>
'프로그래머스 AI 데브코스 5기 > CS' 카테고리의 다른 글
Django로 동적 웹 페이지 만들기 (0) | 2023.04.11 |
---|---|
AWS - RDS 기초 (0) | 2023.04.10 |
AWS EC2 실습 (0) | 2023.04.10 |
AWS 서비스들 (1) | 2023.04.10 |
클라우드 서비스 개요 (0) | 2023.04.09 |