1. 프로젝트 생성 & 앱 생성
(django) ~> django-admin startproject review_01
(django) ~> cd review_01
(django) ~\review_01> python manage.py startapp first_app
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2>
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2>django-admin startproject review_01
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2>cd review_01
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>dir
D 드라이브의 볼륨: OS_WORK
볼륨 일련 번호: 9C64-09D3
D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01 디렉터리
2022-11-02 오후 12:56 <DIR> .
2022-11-02 오후 12:56 <DIR> ..
2022-11-02 오후 12:56 687 manage.py
2022-11-02 오후 12:56 <DIR> review_01
1개 파일 687 바이트
3개 디렉터리 114,693,623,808 바이트 남음
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py startapp first_app
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>dir
D 드라이브의 볼륨: OS_WORK
볼륨 일련 번호: 9C64-09D3
D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01 디렉터리
2022-11-02 오후 12:59 <DIR> .
2022-11-02 오후 12:56 <DIR> ..
2022-11-02 오후 12:59 <DIR> first_app
2022-11-02 오후 12:56 687 manage.py
2022-11-02 오후 12:59 <DIR> review_01
1개 파일 687 바이트
4개 디렉터리 114,693,615,616 바이트 남음
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
2. basic migrate - python manage.py migrate
django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
3. 프로젝트가 앱폴더를 인식하게 연결(앱 내부의 템플릿 폴더를 인식하게 설정)
# review_01/first_app/apps.py
# 장고앱 레벨의 apps.py 파일내용
from django.apps import AppConfig
class FirstAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'first_app'
-------------------------------------------------------------------
# Application definition
# review_01/review_01/settings.py
# 장고앱 레벨의 apps.py 파일에서 정보를 확인한 후, 프로젝트 레벨의 settings.py 파일에 추가
INSTALLED_APPS = [
'first_app.apps.FirstAppConfig', # <=== 앱인식을 위한 추가
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
4. makemigrations - python manage.py makemigrations first_app
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py makemigrations first_app
No installed app with label 'first_app'.
# 지금은 어떤 모델도 가지고 있지 않기 때문에 이런 문구가 출력됩니다
# first_app 앱에서 변경 사항없으므로 감지된것이 없음
# 나중에 실제 모델과 디비에 변경 사항이 있다면 관련 정보를 볼수 있습니다
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
5. migrate - python manage.py migrate
settings.py 설정파일 확인
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], # <=== 현재 프로젝트 레벨 템플릿은 설정되지 않음
'APP_DIRS': True, # <=== 이부분이 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',
],
},
},
]
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
6. 앱view 및 templates 생성
- review_01/first_app/views.py
- review_01/first_app/urls.py
- review_01/review_01/urls.py
- review_01/first_app/views.py
from django.shortcuts import render
from django.http.response import HttpResponse
# Create your views here.
def list_patients(request):
return HttpResponse('patients list')
- review_01/first_app/urls.py
from django.urls import path
from . import views
# domain.com/first_app ---> list of all the patients
urlpatterns = [
path('', views.list_patients, name = 'list_patients'),
]
- review_01/review_01/urls.py
"""review_01 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('first_app/', include('first_app.urls')),
]
- 템플릿으로 처리하는 방법
- review_01/first_app/views.py 수정
- review_01/first_app/templates/first_app/list.html
# review_01/first_app/views.py 수정
from django.shortcuts import render
# from django.http.response import HttpResponse
# Create your views here.
def list_patients(request):
# return HttpResponse('patients list')
return render(request, 'first_app/list.html')
# review_01/first_app/templates/first_app/list.html 생성.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Patients List</title>
</head>
<body>
<h1>Patients List</h1>
</body>
</html>
7. static 설정 및 image 로딩
settings.py 설정파일 확인
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/' # <=== 이부분 있는지 확인 필요
폴더 생성 및 이미지 저장 (./review_01/first_app/static/first_app/ 폴더에 저장)
아래의 static 관련 코드 2군데를 추가하면 된다. load 부분 누락 조심할 것.
# review_01/first_app/templates/first_app/list.html 생성.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Patients List</title>
{% load static %} <!-- # <== 코드 추가 -->
</head>
<body>
<h1>Patients List</h1>
<br><br>
<h2>Example of Static image</h2>
<img src='{% static "first_app/django.jpg" %}' alt = 'my image'> <!-- # <== 코드 추가 -->
</body>
</html>
8. 모델 생성 및 절차
review_01/first_app/models.py 수정
from django.db import models
from django.core.validators import MaxValueValidator,MinValueValidator
# Create your models here.
class Patient(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(120)])
# 추가된 코드, 기본값을 설정한 경우
heartrate = models.IntegerField(default=60,validators=[MinValueValidator(1),MaxValueValidator(300)])
def __str__(self):
return f"{self.last_name}, {self.first_name} is {self.age} years old."
프로젝트 레벨의 settings.py 파일은 이미 수정하였으므로 생략
makemigrations - python manage.py makemigrations first_app
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py makemigrations first_app
Migrations for 'first_app':
first_app\migrations\0001_initial.py
- Create model Patient
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
-------------------------------- 실제 SQL 확인하는 방법 --------------------------------
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py sqlmigrate first_app 0001
BEGIN;
--
-- Create model Patient
--
CREATE TABLE "first_app_patient" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "age" integer NOT NULL, "heartrate" integer NOT NULL);
COMMIT;
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
여기서 바로 모델이 적용되는것은 아니다.
migrate - python manage.py migrate
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, first_app, sessions
Running migrations:
Applying first_app.0001_initial... OK
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>
데이터 생성 - create
(django) D:\workspace\Python\Django\DJANGO4\DJANGO_COURSE_V2\review_01>python manage.py shell
Python 3.10.4 | packaged by conda-forge | (main, Mar 30 2022, 08:38:02) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from first_app.models import Patient
>>>
>>> carl = Patient(first_name='carl', last_name='smith', age=30)
>>> carl.save()
>>>
>>> Patient.objects.create(first_name='susam', last_name='smith', age=40)
<Patient: smith, susam is 40 years old.>
>>>
>>> Patient.objects.create(first_name='mimi', last_name='bolus', age=36)
<Patient: bolus, mimi is 36 years old.>
>>>
>>> mylist=[Patient(first_name='adam', last_name='smith', age=42),Patient(first_name='karl', last_name='marx', age=44),Patient(first_name='edward', last_name='gou', age=46)]
>>>
>>> Patient.objects.bulk_create(mylist)
[<Patient: smith, adam is 42 years old.>, <Patient: marx, karl is 44 years old.>, <Patient: gou, edward is 46 years old.>]
>>>
9. 데이터 읽고 템플릿에 전달 - views.py 와 list.html 파일 수정 필요
views.py 파일 수정
from django.shortcuts import render
from . import models
# Create your views here.
def list_patients(request):
all_patients = models.Patient.objects.all()
context_list = {'patients' : all_patients}
return render(request, 'first_app/list.html', context=context_list)
list.html 파일 수정
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Patients List</title>
{% load static %} <!-- # <== 코드 추가 -->
</head>
<body>
<h1>Patients List</h1>
<br><br>
<h2>Example of Static image</h2>
<img src='{% static "first_app/django.jpg" %}' alt = 'my image'> <!-- # <== 코드 추가 -->
<br><br>
{{patients}}
<br><br>
<ul>
{% for person in patients %}
<li>{{person}}</li>
{% endfor %}
</ul>
</body>
</html>
10. 상속 - base.html 파일을 이용하여 중복 코딩을 생략 가능, 아래 링크 참고
2022.10.27 - [Python/Django] - [Django] Django - 상속(block)
10. url 태크 - 자세한 내용은 아래 링크 참고
2022.10.27 - [Python/Django] - [Django] Django - Tags(url)
'Python > Django' 카테고리의 다른 글
[Django] admin 설정 및 관리 (0) | 2022.11.03 |
---|---|
[Django] 기존 프로젝트에 장고앱 추가 (0) | 2022.11.03 |
[Django] 템플릿과 DB 모델 연결하기 (0) | 2022.11.01 |
[Django] DB - Update, Delete (0) | 2022.11.01 |
[Django] DB - Create(Insert), Read (0) | 2022.10.29 |