본문 바로가기
Back-end/Django

[Django] Django 실습1

by 안녕주 2021. 7. 15.

Django 환경 만들기

python3 -m venv myvenv
source myvenv/bin/activate
pip install django
django-admin startproject firstproject
cd firstproject

App을 만들기

  1.  Django 프로젝트를 이루는 단위
  2. 각각 서비스 별로 분리를 해둔것.
pwd # 현재 위치 확인 후 manage.py가 있는 파일로 가기
python manage.py startapp firstapp[만들고자 하는 앱 이름]

App 등록하기

<규칙 : '앱이름.app.앱이름 첫번째 글자 대문자&Config작성',(콤마 필수)>


웹 사이트 구동 순서

  1. 사용자가 서버에 요청
  2. 서버의 View는 model에게 요청에 필요한 데이터를 받음
  3. view는 받은 데이터를 적절하게 처리해서 template으로 넘김
  4. template은 받은 정보를 사용자에게 보여줌

실습

1. HTML파일들을 따로 모아서관리할 수 있는 templates 폴더를 app폴더에 생성

2. templates 안에 welcome.html 생성후 작성

<div style="text-align: center">
    <h1>사용자의 이름을 입력해주세요</h1>
    <br>
    <form action="">
        <label for="nameInput">이름 : </label>
        <input id="nameInput" name="name">
        <input type="submit" value="제출">
    </form>
</div>

3. firstproject/firstapp/views.py 에서 welcome함수 작성

from django.shortcuts import render

def welcome(request):
    return render(request, 'welcome.html')

4. firstproject/firstproject/urls.py에서 url과 view를 연결한다

from django.contrib import admin
from django.urls import path
from firstapp import views #firstapp에서 views 가져오기

urlpatterns = [
    path('admin/', admin.site.urls), #서버주소 뒤에 admin을 입력하면 해당 사이트로 이동
    path('', views.welcome, name="welcome"), #path(연결할 url주소, view이름, name="welcome")
    #왜 url주소가 비어있냐면 처음에 서버를 가동시키고 처음들어가는 페이지가 welcome이 되게하라는 뜻이다.
    #name은 url대신에 쓸 수 있는 이름
]

5. input박스에 넣은 것을 보여주기 위해 templates 안에 hello.html 작성

<div style="text-align: center">
    <h1>반갑습니다. "이름"님</h1> <!--곧 해결예정-->
</div>

6. views.py에 가서 생성

from django.shortcuts import render

def welcome(request):
    return render(request, 'welcome.html')

def hello(request):
    userName = request.GET['name']  #welcome.html에 있는 것을 가져옴
    return render(request, 'hello.html',{'userName' : userName}) 
    #dic자료형으로 userName이름으로 userName값이 넘어김

7. hello.html에서 이름을 넘겨받기 위해 변수나 제어문을 사용할 수있는 template언어를 사용

<div style="text-align: center">
    <h1>반갑습니다. {{userName}}님</h1>
</div>

8. url.py에 가서 path만들어주기

from django.contrib import admin
from django.urls import path
from firstapp import views 

urlpatterns = [
    path('admin/', admin.site.urls), 
    path('', views.welcome, name="welcome"), 
    path('hello/', views.hello, name="hello"),
]

9. welcome.html의 action 지정

<div style="text-align: center">
    <h1>사용자의 이름을 입력해주세요</h1>
    <br>
    <form action="hello"> <!-- urls.py에서 만든 name="hello"의 hello를 입력하면 적절한 함수가 사용될거다-->
        <label for="nameInput">이름 : </label>
        <input id="nameInput" name="name">
        <input type="submit" value="제출">
    </form>
</div>

10. 서버 돌리기

python manage.py runserver

<사실 값 넘겨주는 부분에서 에러가난다. 문제는 TypeError: 'QueryDict' object is not callable이것인데....흠....>

request.GET['name'] 이렇게 작성해야 했다. .. 나는 () 소괄호를 썼다...


복습

1. App 생성

2. Template 제장

3. View 제작

4. URL 연결

'Back-end > Django' 카테고리의 다른 글

[Django] Django와 데이터베이스  (0) 2021.07.19
[Django] Git 사용법  (0) 2021.07.19
[Django] Django 실습2  (0) 2021.07.15
[Django] MTV 패턴  (0) 2021.07.15
Django Setting  (0) 2021.07.15

댓글