본문 바로가기

Django

02. Django_작업환경설정 복습하기

1. c:\ 하위에 : venv 폴더 생셩 (가상환경 관리 폴더)

2. 파이썬 버전 확인하기
> python --version

==================== 아래 [venv 디렉토리] 위치에서 수행 ==================

3. 가상환경 만들기
> python -m venv venv_django python=3.9.13

4. 가상환경 활성화하기
- 위치 이동 : venv/venv_django/Scripts
>cd venv_django
>cd Scripts
> activate.bat
** 활성화 이후부터 -> 경로 무관하게 > 라이브러리 설치 가능
** 가상환경 라이브러리 설치 위치에 알아서 설치해 줍니다.

==================== 아래 [위치 무관] 수행====================

5. pip 업그레이드 하기
[파이썬만, 아나콘다 업그레이드 필요x]
> python -m pip install --upgrade pip

6. 주피터 노트북 설치하기
> pip install jupyter notebook

6-1. 커널 연결하기
> python -m ipykernel install --user --name venv_django --display-name venv_django_kernel

-- 커널 목록 확인하기
> jupyter kernelspec list

7. 기본 라이브러리 설치하기
> pip install ipython jupyter matplotlib pandas xlrd seaborn scikit-learn
> pip install openpyxl

8. Django 설치하기
> pip install django==4.0.1

================[웹 서버 구축부터는 디렉토리 위치 중요]===================

9. c:\ 하위에 tutorial 폴더 생성하기

10. command 위치를 c:\tutorial\ 위치로 이동하기
> cd /
> cd tutorial

11. Django 프로젝트(웹서버) 생성하기
- config 뒤에 한칸 띄고 점(.) 넣어야 현재 위치에 만들어짐.
> django-admin startproject config .

12. App(앱) 생성하기
- 프로그래밍 영역 (앱은 여러개 만들어서 사용 가능)
- app 의미 : 웹사이트의 카테고리 메뉴별로 프로그램을 나누어서 개발하고자 할때
: app 별로 프로그램을 관리 가능
> django-admin startapp firstapp

13. server 실행하기
> python manage.py runserver

==================[VSCode 실행하기]=====================
14. vscode는 tutorial 위치에서 code 한칸 띄고 점(.)으로 실행
> code .

15. config / settings.py 환경 설정하기
- ALLOWED_HOSTS = ['127.0.0.1']
- INSTALLED_APPS = ['firstapp']
- TEMPLATES = 에서 'DIRS' : [BASE_DIR / 'templates']
- LANGUAGE_CODE = 'ko-kr'
- TIME_ZONE = 'Asia/Seoul'
- STATICFILES_DIRS = [BASE_DIR / 'static']

16. 웹페이지 생성하기 : firstapp / views.py 부터 프로그램 시작
- url을 통해 요청이 들어왔을 때, 처리할 함수 생성하기
- url이 http:127.0.0.1:8000/test 로 요청이 들어오면
- test() 함수를 호출해서 요청에 대한 내용을 브라우저로 전달할겁니다.
-- 라이브러리 추가 : HttpResponse

17. firstapp/view.py에 생성한 함수를 config/urls.py에 매핑하기
- firstapp의 views위치 import 하기
- path('url정의', '함수이름') ==> 함수이름에는 괄호는 없습니다.
- path('test/', 'test')

18. url.py를 config와 app과 분리하기
- first 두번째 구분자 : 앱지정이름
- test  세번째 구분자 : 실제 페이지 함수 호출을 위한 이름

- 사용자 요청 URL : http://127.0.0.1:8000/first/test

- /로 구분된 첫번째 url 이름으로 app을 구분함

- config의 urls.py에서는 app을 구분하기 위한 url이름만 지정
- first 라는 이름의 url이 들어오면, firstapp 폴더 하위의 urls.py 파일 호출
  path('first', include('firstapp.urls'))

- firstapp / urls.py에서 세번째 구분자의 url 이름에 맞는 함수 호출
 * 세번째 구분자 이름 : test
  path('test/', views.test)

19. Templates 폴더 생성하기
- html 파일을 관리하는 곳...
- 생성된 각각의 app에서 각각 만들어야 합니다.
- 생성 규칙 : config/settings.py에 정의한 이름 : templates\앱이름
- firstapp 인 경우 : firstapp/templates\firstapp (역슬래시)

>>> 실습
secondapp에서 템플레이트 폴더 생성
- 01_secondapp_start.html 생성

생성 시, 형식 html으로 변경(VSCode 우측 하단 클릭 후, html 검색 및 적용 -> http:5)
- 함수이름 secondapp_start() 생성
- url : /second/start/

 

config - app 관계, app 안 각 구성요소 확인(urls, views, models)
config 구성
app 구성

★★★ views 에서 함수를 만들고, urls 에서 path 지정 후, config의 urls에서 실행시킨다. ★★★

 

● firstapp 에서의 views 코드

from django.shortcuts import render

### 사용자 브라우저로 응답하는 라이브러리
from django.http import HttpResponse
# Create your views here.

### 02_for.html 읽어들이기
def tableFor(request):
    return render(request,
                  "firstapp/02_for.html",
                  {"id":"a0011", "pw":"pwa0011"})




### Templates / 01_firstapp_start.html 불러들이기
def firstapp_start(request) :
    ### html을 render() 함수에게 전달
    # - render 함수는 html 내에 파이썬 프로그램을
    #   컴파일해서 하나의 html로 변환해주는 역할 수행
    #   동시에 HtppResponse() 까지 수행함.
    return render(request,
        "firstapp/01_firstapp_start.html",
        {})


### test 페이지 함수 생성하기
def test(request) :
    msg = """
            <h3>::: 웹프로그램 성공!! :::</h3>
            <table border='1'>
                <tr>
                    <th>아이디</th>
                    <th>패스워드</th>
                </tr>
                <tr>
                    <td>a001</td>
                    <td>pwa001</td>
                </tr>
            </table>
        """
    ### 브라우저로 전달하는 기능
    return HttpResponse(msg)

### 실습 :
def index1(request):
    return HttpResponse('<u>Hello</u>')
def index2(request):
    return HttpResponse('<u>Hi</u>')
def main(request):
    return HttpResponse('<u>Main</u>')

### 실습 :
def index3(request):
    msg = '<h3>Home</h3>'
    return HttpResponse(msg)

 

● firstapp 에서의 urls 코드

from django.urls import path

from . import views
urlpatterns = [
    ### 페이지마다 하나씩 추가하기
    # http:127.0.0.1:8000/test/ url로 요청이 들어오면,
    # - views.py 파일의 test 함수를 호출합니다.
    # - url과 함수를 매핑한다고 합니다. => url 패턴이라는 용어로 사용
    # path('test/', views.test),
    # path('index1/', views.index1),
    # path('index2/', views.index2),
    # path('main/', views.main),
   
   
   
    ### url : http://127.0.0.1:8000/first/tablefor/
    path('tablefor/', views.tableFor),
   
    ### url : http://127.0.0.1:8000/first/start/
    path('start/', views.firstapp_start),
   
    ### firstapp의 urls.py 호출하기 위한 URL 지정하기
    # http://127.0.0.1:8000/first/test/
    path('test/', views.test),
    path('home/', views.index3),
]

 

● config 에서의 urls 코드

from django.contrib import admin

### include 라이브러리 불러들이기
from django.urls import path, include

### firstapp 폴더의 views.py 파일을 불러들이기
from firstapp import views as firstview
from secondapp import views as secondview

urlpatterns = [
    ### 페이지마다 하나씩 추가하기
    # http:127.0.0.1:8000/test/ url로 요청이 들어오면,
    # - views.py 파일의 test 함수를 호출합니다.
    # - url과 함수를 매핑한다고 합니다. => url 패턴이라는 용어로 사용
    # path('test/', views.test),
    # path('index1/', views.index1),
    # path('index2/', views.index2),
    # path('main/', views.main),
   
    ### firstapp의 urls.py 호출하기 위한 URL 지정하기
    # http://127.0.0.1:8000/first/xxxxx
    path('first/', include('firstapp.urls')),
   
    # http://127.0.0.1:8000/home/
    path('home/', firstview.index3),
   
    # http://127.0.0.1:8000/first/home/
    path('home/', firstview.index3),
    path('first/', include('firstapp.urls')),
    path('admin/', admin.site.urls),
   
    # http://127.0.0.1:8000/second/main/
    path('second/', include('secondapp.urls')),
   
    # http://127.0.0.1:8000/main2/
    path('main2/', secondview.main2),
]

'Django' 카테고리의 다른 글

05. Django_form을 활용한 입력, 입력값 확인  (0) 2023.03.14
04. Django_Include 활용  (0) 2023.03.14
03. Django_ CSS, JS, Image 적용하기  (0) 2023.03.13
01. Django_작업환경설정  (0) 2023.03.09