2
2

More than 3 years have passed since last update.

Djangoで掲示板アプリを1から作るの。(その2)

Posted at

その1
https://qiita.com/TuruMaru/items/4df41577fb9f722c7864

データベースの作成

データベースを作っていくんですが、そのためにはまずmodels.pyにテーブルに内容を書き込んでいく必要があります。

posts/models.py

from django.db import models
#timezoneを使うためにインポート
from django.utils import timezone

# Create your models here.

#models.Modelを書くのはお決まり
class Posts(models.Model):

    #Metaとかobjectとかはおまじない
    class Meta(object):
        #作成されるテーブル名を指定
        db_table = 'posts'

    #カラム名=データの形式(管理画面に表示される名前,その他の制約)
    text = models.CharField(verbose_name='本文', max_length=255)
    created_at = models.DateField(verbose_name='作成日', default=timezone.now)

    #管理画面に表示されるように設定(おまじない)
    def __str__(self):
        return self.text, self.created_at

これでpostsというテーブルを作る準備が完了しました。
これらを元にターミナルで操作していきます。

$ python manage.py makemigrations posts
Migrations for 'posts':
  posts/migrations/0001_initial.py
    - Create model Posts

これで0001_initial.pyファイルが作成されました。
このファイルには作成されるデータベースの内容が書かれています。
ですが、このコマンドではデータベースがまだ作成されていません。準備です。

$ python manage.py sqlmigrate posts 0001
BEGIN;
--
-- Create model Posts
--
CREATE TABLE "posts" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" varchar(255) NOT NULL, "created_at" date NOT NULL);
COMMIT;

このコマンドでテーブルが作成される際のSQLコードが確認できます。

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
  Applying posts.0001_initial... OK

はいこれでできました。ありがとうございます。

管理画面で確認するにはちょっと操作が必要なのですが、ここでは割愛します。

パスを通す

パスを通す作業をしないとせっかく書いたコードがブラウザに表示されませんね。
その他の設定もあるので先にやってしまいましょう。

mysite/setting.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #ここから追加部分
    'posts',
    'templates',
]

アプリケーションを作ったらINSTALLED_APPSに追記しましょう。

settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        #↓ここ1行を追加
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': 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',
            ],
        },
    },
]

templatesディレクトリを作成したのを作成したことをpythonに教えます。

また、動作確認用にviews.pyとhtmlも少し書いておきます。

posts/views.py
from django.shortcuts import render

# Create your views here.
from django.views.generic import View


class IndexView(View):
    def get(self,request, *args, **kwargs):
        return render(request, 'posts/post.html')


index = IndexView.as_view()

templates/base.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>{% block page_title %}{% endblock %}</title>
</head>
<body>
<hr>
<h1>{% block title %}{% endblock %}</h1>
<hr>
{% block content%}{% endblock %}
<hr>
</body>
</html>
templates/posts/post.html
{% extends "base.html" %}
{% block page_title %}post{% endblock %}
{% block title %}post{% endblock %}
{% block content %}
    <h1>Posts</h1>
{% endblock %}

通常、base.htmlを全てのページのベースにしてpost.htmlやらが中身を入れていくっていう感じです。
次はいよいよurls.pyを書いていきます。

mysite/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('posts.urls')),
]
posts/urls.py
from django.urls import path
from . import views

app_name = 'posts'
urlpatterns = [
    path('', views.index, name='index'),
]

こんな感じでかけたらローカルサーバーを立ち上げて確認してみましょう。

$python manage.py runserver 3000

そしてGoogleやらでlocalhost:3000と打ってみましょう。

スクリーンショット 2019-11-04 21.39.07.png

こんな感じで出てきたらパス関係が完成です。
次から掲示板アプリのコードを書いていきましょう。

2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2