Django란 파이썬으로 만들어진 오픈소스 웹 애플리케이션 프레임워크.
# CMD 에서
$ django-admin startproject mysite
$ python manage.py runserver
$ python manage.py startapp polls
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path("polls/", include('polls.urls'))
]
# polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index')
]
# polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world.")
def some_url(request):
return HttpResponse("Some ulr을 구현해 봤습니다.")
]
# polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index')
path('some_url',views.some_url)
]
# mysite/settings.py
...
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls.apps.PollsConfig',
]
...
# 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)
# migration 파일 생성하기
$ python manage.py makemigrations polls
# migration으로 실행될 SQL 문장 살펴보기
$ python manage.py sqlmigrate polls 0001
# migration 실행하기
$ python manage.py migrate
$ python manage.py createsuperuser
# polls/admin.py
from django.contrib import admin
from .models import *
#Register your models here
admin.site.register(Question)
admin.site.register(Choice)
# 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')
def __str__(self):
return f'제목: {self.question_text}, 날짜: {self.pub_date}'
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
# Django Shell 실행하기
$ python manage.py shell
# 위 명령어 실행시 (InteractiveConsole) 뜨면서 >>> 로 바뀜
#models.py 파일에 정의된 모든 모델 가져오기
>>> from polls.models import *
>>> Question
#모든 Question,Choice 오브젝트 가져오기
>>> Question.objects.all()
>>> Choice.objects.all()
#첫번째 Choice 오브젝트 가져오기
>>> choice = Choice.objects.all()[0]
>>> choice.id
>>> choice.choice_text
>>> choice.votes
#첫번째 Choice와 연결된 Question 가져오기
>>> choice.question
>>> choice.question.pub_date
>>> choice.question.id
#해당 Question과 연결되어 있는 모든 Choice 가져오기
>>> question.choice_set.all()
Django 에서 시간을 다룰때는 timezone에 대한 정보가 필요하기 때문에
from django.utils import timezone 를 쓴다.