##現在の環境
- python 3.7
- Django 2.1.7
- mysql
##基本setting
- $django-admin startproject shop
- project start!
- shop = project name
- shop/setting.py からのsetting
- LANGUAGE_CODE = 'ja-jp'
- TIME_ZONE = 'Asia/Tokyo'
- $python manage.py startapp board
- app start!
- board = app name
- shop/setting.py へapp登録
- INSTALLED_APPS = [
'board', <-作ったapp name
......
]
- INSTALLED_APPS = [
- shop/setting.py
- DATEBASEのsetting
DATABASES = {
'default': {
'ENGINE': 'mysql.connector.django',
'NAME': '', #DB Schema name
'USER': '', #DB user
'PASSWORD': '', #DB password
'HOST': 'localhost',
'PORT': '3306',
}
}
-
$python manage.py createsuperuser
- admin siteで使うid/password を設定
- Passwordが易しすぎるのはNG!
-
$python manage.py runserver
- server testing
###掲示板 (Model 作業)
- shop/urls.py でappのviewsとの繋ぎ
from shop import views
urlpatterns = [
url('admin/', admin.site.urls),
url('', views.index, name='index'),
]
- / url(初期画面)で接続したときにshopのviewsに書いているindex methodを呼ぶ
- board/views.py
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('Welcome to my shop!')
- viewsにindex methodを追加
- HttpResponse moduleをimport
Model - Template - Views
- Model : board/models.py
- POST classを作ってformの項目setting
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.CharField(max_length=20)
email = models.CharField(max_length=50)
title = models.CharField(max_length=50)
text = models.TextField()
published_date = models.DataTimeField(
default = timezone.now)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
-
$python manage.py makemigrations board
- DBへ反映できるようにmigration fileを用意
-
$python manage.py migrate board
- DBにtableが作られて内容がsaveされるようにする
-
adminからboardを管理できるように登録
- board/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
App内 Urls ----- Views 作業
- board/urls.py 作成
- /board/ に掲示板を表示するためのURLをsetting
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name = 'post_list'),
]
- board/views.py 作成
- 先のpost_listの定義をsetting
def post_list(request):
return render(request, 'board/post_list.html', {})
- template 作業
- board/template/board forlder作成(boardはApp name)
- board/template/board/post_list.html (作成するhtml)
<html>
<p>Hi there!</p>
<p>Here is post_list page</p>
</html>
- $python manage.py runserver でcheck!