Top / Programming / Python / Django TIPS / 一行掲示板を作成する

一行掲示板を作成する

Djangoの簡単な練習として、一行掲示板を作成します。
Python2.5とDjango1.0.2を使用しました。

プロジェクトの作成

プロジェクトを作成するフォルダでコマンドを実行します。

django-admin startproject example

exampleディレクトリにファイル一式が生成されます。

example/
├__init__.py
├manage.py
├settins.py
└urls.py

アプリケーションの作成

Djangoプロジェクトのディレクトリ(exampleディレクトリ)でコマンドを実行します。

cd example
python manage.py startapp onelinebbs

example/onelinebbsディレクトリにファイル一式が生成されます。

example/ <-このディレクトリでコマンドを実行する
├__init__.py
├manage.py
├settins.py
├urls.py
└onelinebbs/
  ├__init__.py
  ├models.py
  └views.py

アプリケーションを作成したら、settings.pyのINSTALLED_APPSに登録します。

example/
├__init__.py
├manage.py
├settins.py <-このファイルを編集する
├urls.py
└onelinebbs/
  ├__init__.py
  ├models.py
  └views.py

INSTALLED_APPSにアプリケーションを追加します。

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'onelinebbs', #<-追加する
)

データベースの設定

settings.pyを編集して、データベースの設定を行います。
SQLite3を使用します。

example/
├__init__.py
├manage.py
├settins.py <-このファイルを編集
├urls.py
└onelinebbs/
  ├__init__.py
  ├models.py
  └views.py

settings.pyのDATABASE_ENGINEとDATABASE_NAMEを編集します。

import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(BASE_DIR, 'data.db')
#DATABASE_ENGINE = ''           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
#DATABASE_NAME = ''             # Or path to database file if using sqlite3.

ついでに、TIME_ZONEとLANGUAGE_CODEも編集しましょう。

#TIME_ZONE = 'America/Chicago'
TIME_ZONE  = 'Japan/Tokyo'

#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'ja-jp'

モデルの作成

モデルを作成します。

onelinebbs/models.pyを編集します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
└onelinebbs/
  ├__init__.py
  ├models.py <-このファイルを編集
  └views.py

ファイルの文字コードはUTF-8にします。

# -*- coding: utf-8 -*-
from django.db import models
import datetime

class Entry(models.Model):
    # コメント
    comment = models.CharField(u'コメント', max_length=200, blank=False)
    # 登録日時
    pub_date = models.DateTimeField(u'登録日時', auto_now_add=True, editable=False)

    def __unicode__(self):
        return self.comment

Django管理サイト(Adminサイト)の設定

モデルの編集を行うDjango管理サイト(Adminサイト)を有効化します。

settings.pyを編集します。

example/
├__init__.py
├manage.py
├settins.py <-このファイルを編集
├urls.py
└onelinebbs/
  ├__init__.py
  ├models.py
  └views.py

INSTALLED_APPSに'django.contrib.admin'を追加します。

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'onelinebbs',
    'django.contrib.admin', #<-追加する
)

urls.pyを編集します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py <-このファイルを編集
└onelinebbs/
  ├__init__.py
  ├models.py
  └views.py

Django管理サイト(Adminサイト)のコメントを解除します。

from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
)

データベースのテーブルの作成

Djangoプロジェクトのディレクトリ(exampleディレクトリ)で次のコマンドを実行します。

python manage.py syncdb

Djangoの認証システムのスーパーバイザを登録するか、聞いてきます。

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no):

後から登録することもできますが、ここで登録しておきます。
ユーザー名、メールアドレス、パスワードを入力します。

Django管理サイトのログイン

Djangoプロジェクトのディレクトリ(exampleディレクトリ)で次のコマンドを実行し、テスト用のWebサーバを起動します。

python manage.py runserver

Webブラウザでhttp://127.0.0.1:8000/admin/にアクセスします。

Django管理サイトのログイン画面が表示されたら、先ほど入力したユーザ名とパスワードを入力してログインします。

Django管理サイトにモデルを登録

Django管理サイトにモデルを登録します。

onelinebbs/admin.pyを作成します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
└onelinebbs/
  ├__init__.py
  ├admin.py <-このファイルを作成
  ├models.py
  └views.py

次のコードを入力します。

# -*- coding: utf-8 -*-
from django.contrib import admin
from example.onelinebbs.models import Entry

class EntryAdmin(admin.ModelAdmin):
    pass

admin.site.register(Entry, EntryAdmin)

再びWebブラウザでDjango管理サイト(http://127.0.0.1:8000/admin/)にアクセスします。

Onelinebbsの項目が追加されて、Entrysを編集することができるようになっています。

試しにEntryの追加や編集、削除を行ってください。

登録済みのコメントの一覧表示

登録済みのコメントを一覧表示する画面を作成します。

onelinebbs/views.pyを編集します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
└onelinebbs/
  ├__init__.py
  ├admin.py
  ├models.py
  └views.py <-このファイルを編集

登録されているコメントを新しいものから5件取得する処理を追加します。
テンプレートファイルは'onelinebbs/index.html'を使用します。

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from example.onelinebbs.models import Entry

def index(request):
    entry_list = Entry.objects.all().order_by('-id')[:5]
    return render_to_response('onelinebbs/index.html',
                              {'entry_list': entry_list})

settings.pyを編集して、テンプレートファイルを配置するディレクトリを登録します。

example/
├__init__.py
├manage.py
├settins.py <-このファイルを編集
├urls.py
└onelinebbs/
  ├__init__.py
  ├admin.py
  ├models.py
  └views.py

TEMPLATE_DIRSにtemplatesディレクトリを登録します。

データベースの設定の時に、定数BASE_DIRを設定しています。
定数BASE_DIRを使用して、templatesディレクトリを登録します。

import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

…

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates')
)

テンプレートファイルを作成します。
templates/onlinebbs/index.htmlを作成します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
├onelinebbs/
│├__init__.py
│├admin.py
│├models.py
│└views.py
└templates/ <-ディレクトリを作成
  └onelinebbs/ <-ディレクトリを作成
    └index.html <-ファイルを作成

templates/onlinebbs/index.htmlを編集します。

<html>
<head>
<title>一行掲示板</title>
</head>
<body>
<ul>
{% for entry in entry_list %}
  <li>{{ entry.comment }}({{ entry.pub_date|date:"Y年m月d日h時i分s秒" }})</li>
{% endfor %}
</ul>
</body>
</html>

urls.pyを編集して、URLを割り当てます。

example/
├__init__.py
├manage.py
├settins.py
├urls.py <-このファイルを編集
├onelinebbs/
│├__init__.py
│├admin.py
│├models.py
│└views.py
└templates/
  └onelinebbs/
    └index.html

patternsに追加します。
ルートディレクトリに割り当てます。

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
    (r'', 'onelinebbs.views.index'),
)

Webブラウザでhttp://127.0.0.1:8000/にアクセスします。

登録されているEntryが新しいものから順に5件表示されます。

コメントの登録処理

templates/onlinebbs/index.htmlを編集します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
├onelinebbs/
│├__init__.py
│├admin.py
│├models.py
│└views.py
└templates/
  └onelinebbs/
    └index.html <-このファイルを編集

入力フォームを追加します。

<html>
<head>
<title>一行掲示板</title>
</head>
<body>
<form action="./" method="post">
{% if errors %}
<dl>
  <dt>エラーがあります。</dt>
{% for error in errors %}
  <dd>{{ error }}</dd>
{% endfor %}
</ul>
{% endif %}
  <label for="id_comment">コメント:</label>
  <input id="id_comment" type="text" name="comment" maxlength="200" />
  <input type="submit" value="投稿する" />
</form>

<ul>
{% for entry in entry_list %}
  <li>{{ entry.comment }}({{ entry.pub_date|date:"Y年m月d日h時i分s秒" }})</li>
{% endfor %}
</ul>
</body>
</html>

変数errorsにはエラーメッセージが格納されます。

onelinebbs/views.pyを編集します。

example/
├__init__.py
├manage.py
├settins.py
├urls.py
├onelinebbs/
│├__init__.py
│├admin.py
│├models.py
│└views.py <-このファイルを編集
└templates/
  └onelinebbs/
    └index.html

コメントの登録処理を追加します。

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from example.onelinebbs.models import Entry

def index(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('comment', ''):
            errors.append('コメントが未入力です。')
        if not errors:
            Entry(comment = request.POST['comment']).save()
    entry_list = Entry.objects.all().order_by('-id')[:5]
    return render_to_response('onelinebbs/index.html',
                              {'entry_list': entry_list,
                               'errors': errors})

Webブラウザでhttp://127.0.0.1:8000/にアクセスします。

コメントを入力し投稿ボタンをして、登録されることを確認します。

以上で完成です。

更新履歴