プロジェクトの作成

はじめてのDjangoアプリ作成のチュートリアルをやったときのメモです。
なので、はじめてのDjangoアプリ作成のほうが詳しく載ってるので、そちらを参考にされたほうがよいかと思います。

http://michilu.com/django/doc-ja/index/ こっちが新しいドキュメントだそうです。ご注意ください。

プロジェクトの作成

# django-admin.py startproject sample
# cd sample
# python manage.py runserver

Setting.pyの編集

# vim settings.py
DATABASE_ENGINE = 'postgresql_psycopg2'   # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '***'                     # Or path to database file if using sqlite3.
DATABASE_USER = '***'                     # Not used with sqlite3.
DATABASE_PASSWORD = '***'                 # Not used with sqlite3.
DATABASE_HOST = 'localhost'               # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''                        # Set to empty string for default. Not used with sqlite3.

PostgreSQLのDB作成

# createuser -U postgres -P ***
# createdb -E UTF-8 ***

PostgreSQLのライブラリを認識させる

# cd  /etc/ld.so.conf.d/
# vim psycopg2.conf
/usr/local/pgsql/lib
# ldconfig 

※設定をしていないと、以下のようなエラーが起きる。

# python manage.py syncdb
Traceback (most recent call last):
 File "manage.py", line 11, in <module>
   execute_manager(settings)
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/__init__.py", line 272, in execute_manager
   utility.execute()
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/__init__.py", line 219, in execute
   self.fetch_command(subcommand).run_from_argv(self.argv)
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/base.py", line 72, in run_from_argv
   self.execute(*args, **options.__dict__)
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/base.py", line 85, in execute
   self.validate()
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/base.py", line 112, in validate
   num_errors = get_validation_errors(s, app)
 File "/usr/local/python/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
   from django.db import models, connection
 File "/usr/local/python/lib/python2.5/site-packages/django/db/__init__.py", line 17, in <module>
   backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
 File "/usr/local/python/lib/python2.5/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 15, in <module>
   raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: libpq.so.5: cannot open shared object file: No such file or directory

Djangoが使うDB作成

# 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 'root'): user
E-mail address: mail
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Message model
Installing index for auth.Permission model

※DBを見てみると、以下のようにDBが作成されている。

                      List of relations
 Schema |               Name                |   Type   | 
--------+-----------------------------------+----------+-
 public | auth_group                        | table    | 
 public | auth_group_id_seq                 | sequence | 
 public | auth_group_permissions            | table    | 
 public | auth_group_permissions_id_seq     | sequence | 
 public | auth_message                      | table    | 
 public | auth_message_id_seq               | sequence | 
 public | auth_permission                   | table    | 
 public | auth_permission_id_seq            | sequence | 
 public | auth_user                         | table    | 
 public | auth_user_groups                  | table    | 
 public | auth_user_groups_id_seq           | sequence | 
 public | auth_user_id_seq                  | sequence | 
 public | auth_user_user_permissions        | table    | 
 public | auth_user_user_permissions_id_seq | sequence | 
 public | django_content_type               | table    | 
 public | django_content_type_id_seq        | sequence | 
 public | django_session                    | table    | 
 public | django_site                       | table    | 
 public | django_site_id_seq                | sequence | 
(19 rows)


Model

モデルの作成

アプリケーションを作成

# python manage.py startapp polls

モデル作成

# vim polls/models.py
from django.db import models

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

    def __unicode__(self):
        return self.question

    class Admin:
        pass

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

    def __unicode__(self):
        return self.choice

    class Admin:
        pass

モデルを有効にする

INSTALLED_APPSに「sample.polls」を追加

# vim settings.py 

CRATE TABLE SQL文を表示

# python manage.py sql polls

テーブル作成

# python manage.py syncdb

API

API起動

# python manage.py shell


Adminサイト

Adminサイトの有効化

INSTALLED_APPSに「django.contrib.admin」を追加

# vim settings.py

DBの更新

# python manage.py syncdb 

URLconfの設定

# vim urls.py
urlpatterns = patterns('',
    (r'^admin/', include('django.contrib.admin.urls')),
)

開発サーバの起動

以下のコマンドを実行し、http://127.0.0.1:8000/admin/ にアクセスする。

# python manage.py runserver

モデルを編集し任意のAdminサイトを表示する

# vim polls/models.py
class Poll(models.Model):
   # ...
   class Admin:
       pass


View

Viewの作成

# vim polls/views.py
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world.")

テンプレートの場所「TEMPLATE_DIRS」を設定する

# vim settings.py
TEMPLATE_DIRS = (
   "/home/user/templates",
)

テンプレートの作成

# vim /templates/polls/index.html

urls.pyのコピー

# cp urls.py polls/urls.py

urls.py(sample/urls.py)に以下の1行を記述する

# vim urls.py
urlpatterns = patterns('sample.polls.views',
    (r'^polls/', include('sample.polls.urls')),
)

urls.py(sample/polls/urls.py)に以下を記述する

# vim polls/urls.py
urlpatterns = patterns('sample.polls.views',
     (r'^admin/', include('django.contrib.admin.urls')),
     (r'^$', 'index'),
     (r'^(?P<poll_id>\d+)/$', 'detail'),
)

URLメモ

http://localhost:8000/polls/admin/
http://localhost:8000/polls/
http://localhost:8000/polls/1
http://localhost:8000/polls/1/vote/
http://localhost:8000/polls/1/results/


Comment



Counter: 12066, today: 1, yesterday: 0

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2013-09-24 (火) 14:56:28 (1310d)