티스토리 뷰
📌 Django 프로젝트(3)
👉 프로젝트에 Application 추가하기
필요한 라이브러리 설치와 디렉토리 설정을 마쳤다면 이번에는 Django 프로젝트를 생성하며 자동 설정된 setting.py 를 필요에 맞게 수정하자. time zone은 현재 국가와 맞춰주고, Django와 연결할 데이터베이스 계정 정보를 수정해주어야한다.
1. application 통합 template 디렉토리 templates 만들기
- 디렉토리 생성 : Pycharm 프로젝트 폴더 안에 templates 생성
- 디렉토리 설정 : setting.py 에서 templates 디렉토리를 설정
# import os
'DIRS' : [os.path.join(BASE_DIR, 'templates']
2. hello world
(1) 어플리케이션 생성
(venv) # python manage.py startapp helloworld
(2) 어플리케이션 등록 : setting.py 에 어플리케이션 등록
INSTALLED_APPS = [
'helloworld', # 생성한 어플리케이션 이름 추가
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
(3) 어플리케이션 template 디렉토리 생성
- templates 폴더안에 application과 이름이 동일한 폴더를 생성하고, 그 안에 test.html 파일 생성
(4) views.py(어플리케이션) 에 요청 처리 함수 생성
from django.http import HttpResponse
from django.shortcuts import render
def main(request):
# main함수가 실행되면 test.html파일이 열리도록 render
return render(request, 'helloworld/test.html')
def hello1(request):
# hello1함수가 실행되면 변수 contents에 저장된 html 코드가 웹에 적용
contents = '<h1>Hello1</h1>'
return HttpResponse(contents, content_type='text/html; charset=utf-8')
(5) urls.py(프로젝트) 에 url 등록(path) : 모듈의 형태로 불러오기
- views.py에 생성한 함수를 url.py 에 등록
from django.contrib import admin
from django.urls import path
import helloworld.views as helloworldviews # 모듈을 사용하듯 import
urlpatterns = [
# path('경로', views.py에 만들어둔 함수)
path('', helloworldviews.main), # index.html의 역할
path('hello1/', helloworldviews.hello1),
path('admin/', admin.site.urls) # 기본 path
]
(6) 서버를 활성화해서 확인해보자 (http://localhost:9999)
(venv) # python manage.py runserver 0.0.0.0:9999
'BackEnd > Django' 카테고리의 다른 글
[Django] Pycharm에서 Django (2) (0) | 2021.07.05 |
---|---|
[Django] Pycharm에서 Django (1) (0) | 2021.07.05 |
댓글