はじめての Django アプリ作成

一からリトライ。ざくっと流します。

まずプロジェクト作る

プロジェクト作成は django-admin.py

$ django-admin.py startproject mysite
$ cd mysite
$ ls
__init__.py  __init__.pyc  manage.py  settings.py  urls.py
$

テキストによれば、コードはドキュメントルートには置くな、との事。このあたりは RoR なんかと同じカンジと言っても良いのでしょうか。
ええといくつか要点を以下に控え

  • __init__.py はココが python なパケジである目印
  • manage.py はユーティリティー
  • settings.py は設定なソレ
  • urls.py は ある意味 dispather 的な目印
  • 開発サーバの起動は _python manage.py runserver_ で
  • デフォルトでは http://localhost:8000/ でナニ

DB 設定

settings.py で。sqlite3 なソレは以下

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/home/guest/django/mysite/mysite.db'

で、syncdb すればナニ

$ python manage.py syncdb
Creating table auth_message
Creating table auth_group
Creating table auth_user
Creating table auth_permission
Creating table django_content_type
Creating table django_session
Creating table django_site

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): yes
Username (Leave blank to use 'guest'): guest
E-mail address: guest
Error: That e-mail address is invalid.
E-mail address: yamanetoshi@gmail.com
Password: 
Password (again): 
Superuser created successfully.
Installing index for auth.Message model
Installing index for auth.Permission model
Loading 'initial_data' fixtures...
No fixtures found.
$

最初は管理ユーザの user/pass 云々なソレをナニ。デキた table は以下

sqlite> .tables
auth_group                  auth_user_groups          
auth_group_permissions      auth_user_user_permissions
auth_message                django_content_type       
auth_permission             django_session            
auth_user                   django_site               
sqlite> 

一応 settings.py がデフォルトなまんまなので、なのかな。settings.py の INSTALLED_APPS は現時点では以下

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)

次行きます。

モデルの作成

ええと、まずアプリケーションを作成、と。

$ python manage.py startapp polls 

で、polls/models.py を以下に修正

from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()

とりあえず、前の失敗を踏まえて validate

$ python manage.py validate polls
0 errors found.
$

OK と見て以下

$ python manage.py sql polls
Traceback (most recent call last):
  File "manage.py", line 11, in ?
    execute_manager(settings)
  File "/usr/lib/python2.4/site-packages/django/core/management.py", line 1672, in execute_manager
    execute_from_command_line(action_mapping, argv)
  File "/usr/lib/python2.4/site-packages/django/core/management.py", line 1620, in execute_from_command_line
    mod_list = [models.get_app(app_label) for app_label in args[1:]]
  File "/usr/lib/python2.4/site-packages/django/db/models/loading.py", line 46, in get_app
    raise ImproperlyConfigured, "App with label %s could not be found" % app_label
django.core.exceptions.ImproperlyConfigured: App with label polls could not be found
$

げ。資料をよく見てみると INSTALLED_APPS なソレを修正してませんでした。以下をナニ

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'mysite.polls',
)

で、再度

$ python manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
    "id" integer NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" datetime NOT NULL
);
CREATE TABLE "polls_choice" (
    "id" integer NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
COMMIT;

オーゲー。syncdb する

$ python manage.py syncdb
Creating table polls_poll
Creating table polls_choice
Installing index for polls.Choice model
Loading 'initial_data' fixtures...
No fixtures found.
$

テーブル二つできている模様。こんどは choice になっていますな。(恥

API で遊ぶ

あんまり遊んでるヒマはないんですが、適当にヤッててスルーでハマったからな。とりあえずざっくり以下

$ python manage.py shell
Python 2.4.4 (#2, Apr  5 2007, 20:11:18) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite.polls.models import Poll, Choice
>>> 
>>> from datetime import datetime
>>> p = Poll(question="What's up?",pub_date=datetime.now())
>>> p.save()
>>> p.id
1
>>> p
<Poll: Poll object>
>>> 

で、polls/models.py を以下に

from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()
    def __str__(self):
        return self.choice

で、shell 上で import したら OK なのだと思ってたら違う模様。一旦終了して再開。

$ python manage.py shell
Python 2.4.4 (#2, Apr  5 2007, 20:11:18) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: What's up?>]
>>> 

もう少し

$ python manage.py shell
Python 2.4.4 (#2, Apr  5 2007, 20:11:18) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: What's up?>]
>>> p = Poll.objects.get(pk=1)
>>> p.choice_set.create(choice='Not much',votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky',votes=0)
<Choice: The sky>
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>]
>>> 

一応これで OK ってコトで次。

admin

ええと[その 2]によると admin なソレを有効化するには以下が必要との事

  • settings.py の INSTALLED_APPS に "django.contrib.admin" 追加
  • syncdb する
  • urls.py の "Uncomment this for admin:" の下をコメントアウト解除

で、サーバ起動か。一応ログイン OK

モデルの admin 編集

polls/models.py を以下にしてみた

from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question
    class Admin:
        pass

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()
    def __str__(self):
        return self.choice
    class Admin:
        pass

で、http://localhost:8000/admin/ を reload すれば Choices と Polls なソレが出てきた。ここはスルーしてたんですが、再度スルー。ニュース投稿なソレで色々な know-how は feedback されてそげに見える。

そろそろ限界

とりあえず gdgd になりそうなので。職場にここマデのナニを tar で固めて送ってやれ (を
こんな微妙なナニではなく当初の目論見な RSS リーダあたりを、なんですが。