설문조사(Polls) 어플리케이션을 만들면서 django를 배웠습니다.
Django 첫 번째 장고 앱 작성하기
파이썬의 웹 프레임워크 Django의 프로젝트를 생성하면 아래처럼 디렉토리가 생성됩니다.
django-admin startproject mysite
manage.py를 통해 개발 서버를 실행할 수 있습니다.
python manage.py runserver
단 개발 서버는 오직 개발 목적으로 사용!!
Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
4월 06, 2021 - 15:50:53
Django version 3.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
이 서버는 실행한 컴퓨터 웹 브라우저에서 http://127.0.0.1:8000 으로 접속할 수 있습니다.
이 url로 접속했을 때 로켓이 담긴 페이지를 보면 성공입니다.
프로젝트 디렉토리 안에 앱 디렉토리를 만들 수 있습니다.
python manage.py startapp polls
이 명령어를 치면 프로젝트 디렉토리 안에 polls라는 디렉토리가 생긴 것을 확인할 수 있습니다.
이제 polls 앱의 url을 추가하여 polls 앱의 view를 웹 브라우저에 호출할 것입니다.
- http://127.0.0.1:8000/polls url 추가
- 위 링크로 들어갔을 때 polls 앱안의 urls.py 접근
- polls.urls는 views.py로 접근해서 index 함수에서 return값 호출
# mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite안의 urls.py에서 path를 통해 polls/로 접근할 수 있는 url을 추가해줍니다.
include안의 polls(앱)의 urls.py에게 요청합니다.
polls 앱에 urls.py를 생성해서 url을 호출했을 때 polls 앱에 접근할 수 있도록 합니다.
# 터미널
touch urls.py
# polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
path에서 url이 ''값이기 때문에 바로 views.index에게 요청합니다.
# polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
마지막으로 index 함수가 url호출에 응답하여 HttpResponse안의 값이 return되어 웹페이지에 보여집니다.
python manage.py runserver