- 이 튜토리얼은 django 3.1 버전을 기반으로 실행됩니다.
시작할 폴더 위치를 만들고 다음 명령어 입력
django-admin startproject mysite
[실행 결과]
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
- mysite : 프로젝트의 container (이름 바꿔도 무관)
- manage.py : command-line utility
- init.py : 이 directory가 python pakcage임을 명시
- settings.py : django project 세팅
- urls.py : project의 url 선언
- asgi.py : An entry-point for ASGI-compatible web servers
- wsgi.py : An entry-point for WSGI-compatible web servers
- 서버 실행
py manage.py runserver - 포트 옵션
py manage.py runserver 8080
프로젝트 내부 app 생성
manage.py와 같은 폴더에서 명령어 실행
py manage.py startapp polls
[실행 결과]
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
view 작성
polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
mysite/url.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
include() 함수는 다른 URLconfs를 참조하도록 허용한다. admin.site.urls만 예외
path() 함수는 4개의 변수를 보내는데 route, view는 필수고 kwargs, name은 옵션이다.
- route : URL pattern을 포함한 문자열. 패턴은 GET이나 POST의 파라미터들이나 도메인 이름을 찾지 않는다.
- view : django가 맞는 pattern을 찾으면 HttpRequest 객체로 특정한 view function을 호출한다.
- kwargs : Arbitrary keyword arguments can be passed in a dictionary to the target view\
- name : 하나의 파일만 닿을 수 있도록 이름 지정
settings.py 구성
- TIME_ZONE : time zone 구성
- INSTALLED_APPS : 기본 설치 앱
- django.contrib.admin - 관리자 페이지
- django.contrib.auth - 보완 시스템
- django.contrib.contenttypes - framework content types
- django.contrib.sessions - session framework
- django.contrib.messages - messaging framework
- django.contrib.staticfiles - 정적 파일 관리 framework
database 세팅
다른 벤더사를 쓸 수 있다. 이번 튜토리얼을 sqllite로 진행 (프로젝트내에 포함)
ex) 다른 벤더사 세팅 시 settings.py에 작성
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xe',
'USER': 'a_user',
'PASSWORD': 'a_password',
'HOST': 'dbprod01ned.mycompany.com',
'PORT': '1540',
}
}
필수 테이블 구성
py manage.py migrate
polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
각각의 model은 django.db.models.Model로 표현된다.
- CharFiled (character field)
- DateTimeField (datetimes)
- IntegerField (int)
question_text, pub_date 데이터 베이스 컬럼명으로 사용
model은 database schema를 만들고, python database-access API를 만든다.
- app을 project에 포함시키려면 INSTALLED_APPS 세팅에 추가해줘야한다.
PollsConfig class는 polls/app.py 파일 안에 있기 때문에 poll.apps.PollsConfig로 지정한다.
mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
- makemigrations : model에 변경이 있음을 Django에 알려준다. (migration 생성)
py manage.py makemigrations polls
polls/migrations/0001_initial.py 파일에 남겨진다.
- sqlmigrate : migrate할 sql 구문을 보여준다. (실제 migration은 아니다.)
py manage.py sqlmigrate polls 0001 - migration이 안되었거나 database를 만졌는지 확인하는 명령
py manage.py check - migrate : 전체 migration
py manage.py migrate
Python shell을 이용한 작업
py manage.py shell
manage.py가 DJANGO_SETTINGS_MODULE 변수에 mysite/settings.py 파일을 넣는다.
from polls.models import Choice, Question
Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save() //저장
q.id //아이디 조회
q.question_text //텍스트 조회
q.pub_date //날짜 조회
q.question_text = "What's up?"
q.save() //변경
Question.objects.all()
- model 함수를 통해 return object 표시 변경
polls/models.py
from django.db import models
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
from polls.models import Choice, Question
# Make sure our __str__() addition worked.
Question.objects.all()
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
Question.objects.filter(id=1)
Question.objects.filter(question_text__startswith='What')
# Get the question that was published this year.
from django.utils import timezone
current_year = timezone.now().year
Question.objects.get(pub_date__year=current_year)
# Request an ID that doesn't exist, this will raise an exception.
Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
Question.objects.get(pk=1)
# Make sure our custom method worked.
q = Question.objects.get(pk=1)
q.was_published_recently()
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
q.choice_set.all()
# Create three choices.
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
# Choice objects have API access to their related Question objects.
c.question
# And vice versa: Question objects get access to Choice objects.
q.choice_set.all()
q.choice_set.count()
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (reusing the 'current_year' variable we created above).
Choice.objects.filter(question__pub_date__year=current_year)
# Let's delete one of the choices. Use delete() for that.
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete()
기존 db를 models.py로 바꾸는 법
py manage.py inspectdb --database [settings.py에 지정한 database명] > models.py
Django Admin
계정 생성 명령
py manage.py createsuperuser
물어보는 내용에 따라 계정 정보 입력
my-site/settings.py LANGUAGE_CODE에서 언어 변경 가능 (ko-KR). 언어 코드표
주소/admin으로 관리자 페이지 접속
관리자 페이지에 polls 추가
polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
출처
https://docs.djangoproject.com/en/3.1/intro/tutorial01/ https://docs.djangoproject.com/en/3.1/intro/tutorial02/