| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Django 最初のアプリケーション 2

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

Django 最初のアプリケーション 2 (Admin サイトの構築)

[Python][Django][[Django 最初のアプリケーション 3]|[前|Django 最初のアプリケーション 1]]][[[次]]

Pythonの概要も分かり易い.

を参考にサンプルアプリケーションを作成してみる

Admin サイトを有効化

  • DjangoのAdminサイトはデフォルトでは有効でない

有効化手順

"django.contrib.admin" を INSTALLED_APPS セッティングに追加する
  1. INSTALLED_APPS = (
  2. 'django.contrib.auth',
  3. 'django.contrib.contenttypes',
  4. 'django.contrib.sessions',
  5. 'django.contrib.sites',
  6. 'django.contrib.admin',
  7. 'mysite.polls'
  8. )
python manage.py syncdb を実行。データベースが更新される必要がある
  1. # python manage.py syncdb
  2. Creating table django_admin_log
  3. Installing index for admin.LogEntry model
mysite/urls.py ファイルを編集し、"Uncomment the next two lines..." 以下のコメントをはずす
  1. from django.conf.urls.defaults import *
  2.  
  3. # Uncomment the next two lines to enable the admin:
  4. from django.contrib import admin # <- コメントはずす
  5. admin.autodiscover() # <- コメントはずす
  6.  
  7. urlpatterns = patterns(,
  8. # Example:
  9. # (r'^mysite/', include('mysite.foo.urls')),
  10.  
  11. # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
  12. # to INSTALLED_APPS to enable admin documentation:
  13. # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
  14.  
  15. # Uncomment the next line to enable the admin:
  16. (r'^admin/(.*)', admin.site.root), # <- コメントはずす
  17. )

開発サーバー起動

  • アドレスとポートを指定して起動
  1. # python manage.py runserver 192.168.24.14:8080
  2. Validating models...
  3. 0 errors found
  4.  
  5. Django version 1.0.2 final, using settings 'mysite.settings'
  6. Development server is running at http://192.168.24.14:8080/
  7. Quit the server with CONTROL-C.

Adminサイトへログイン

アクセス http://ホスト:ポート/admin/

0354 django firstapp06.jpg

Django 最初のアプリケーション 1で設定したユーザIDとパスワードでログイン

0355 django firstapp07.jpg

作成した、PollオブジェクトをAdminサイトに追加する

  • mysite/polls に admin.py ファイルを作成し、以下の内容を記述
  1. from mysite.polls.models import Poll
  2. from django.contrib import admin
  3.  
  4. admin.site.register(Poll)
  • サーバーを再起動

機能の確認

  • Pollを登録したのでDjangoのインデックスページに表示される

0356 django firstapp08.jpg

  • Pollsをクリックすると、チェンジリストページが開く。このページでは、データベース上のすべてのPollsが表示される
  • そのうちの1つを選択して変更することができる

0357 django firstapp09.jpg

  • 編集するために、"What's up"を選択

0358 django firstapp10.jpg

覚書
  • Poll モデルから、form は自動生成される
  • モデルのフィールド型(DateTimeField, CharField)は、適切なHTMLのInputタグとして表示される
  • DateTimeField は、"Today" リンクや、カレンダーポップアップへのリンクが表示され、時間の場合、"Now"リンクや、時間を選択するポップアップへのリンクが表示される
画面下部のオプション 内容
Save 保存して、チェンジリストへ戻る
Save and continue editing 保存して、リロード
Save and add other 保存して、ブランクページを開く
Delete 削除確認へ

Admin Form のカスタマイズ

  • admin form の見た目や働きをカスタマイズしたい場合、/mysite/polls/admin.py を以下のように変更する

フィールドの表示順を変更する

  1. from mysite.polls.models import Poll
  2. from django.contrib import admin
  3.  
  4. #以下を追加
  5. class PollAdmin(admin.ModelAdmin):
  6. fields = ['pub_date', 'question']
  7.  
  8. #PollAdmin引数を追加
  9. admin.site.register(Poll,PollAdmin)

0359 django firstapp11.jpg

フィールドが多数ある場合など、フィールドセットに分割

  1. class PollAdmin(admin.ModelAdmin):
  2. fieldsets = [(None, {'fields':['question']}),
  3. ('Date information', {'fields':['pub_date']}),
  4. ]

0360 django firstapp12.jpg

開閉可能にする

  • Djangoが提供する collapse クラスを使用する
  1. class PollAdmin(admin.ModelAdmin):
  2. fieldsets = [(None, {'fields':['question']}),
  3. ('Date information', {'fields':['pub_date'],'classes':['collapse']}),
  4. ]

0361 django firstapp13.jpg 0362 django firstapp14.jpg

関連オブジェクトの追加

  • Poll は複数の Choice 持つが、Pollの adminページでは Choice が表示されていない。
1つ目の方法
  • Pollと同様Choiceも adminに 追加する
  1. from mysite.polls.models import Poll, Choice
  2.  
  3. from django.contrib import admin
  4.  
  5. class PollAdmin(admin.ModelAdmin):
  6. fieldsets = [
  7. (None , {'fields':['question']}),
  8. ('Date information', {'fields':['pub_date'],'classes':['collapse']}),
  9. ]
  10. admin.site.register(Poll,PollAdmin)
  11. admin.site.register(Choice)
  • Choiceの追加に、Pollを指定するオプションが表示される

0363 django firstapp15.jpg

  • Djangoは外部キーを把握しており、プルダウンにすべてのPollを選択可能にする
2つ目の方法
  • 1つ目の方法は非効率。Pollオブジェクトから、Choiceオブジェクトを追加できるようにするには、以下のようにする
  1. from mysite.polls.models import Poll, Choice
  2. from django.contrib import admin
  3.  
  4. class ChoiceInline(admin.StackedInline):
  5. model = Choice
  6. extra = 3
  7.  
  8. class PollAdmin(admin.ModelAdmin):
  9. fieldsets = [
  10. (None , {'fields':['question']}),
  11. ('Date information', {'fields':['pub_date'],'classes':['collapse']}),
  12. ]
  13. inlines = [ChoiceInline]
  14.  
  15. admin.site.register(Poll,PollAdmin)
  16. #admin.site.register(Choice)

0364 django firstapp16.jpg

  • StackedInline -> TabularInline に変更すると、以下のような表示になる
  1. class ChoiceInline(admin.TabularInline):

0365 django firstapp17.jpg

チェンジリストのカスタマイズ

一覧にカラムを表示

  • Djangoではデフォルトで、オブジェクトの str() メソッドを一覧に表示しているが、役に立つ別のフィールドを list_display オプションを利用して表示することもできる
  1. class PollAdmin(admin.ModelAdmin):
  2. fieldsets = [
  3. (None , {'fields':['question']}),
  4. ('Date information', {'fields':['pub_date'],'classes':['collapse']}),
  5. ]
  6. inlines = [ChoiceInline]
  7. # この行を追加
  8. list_display = ('question', 'pub_date', 'was_published_today')

0366 django firstapp18.jpg

カラムの名称を変更

  • カラムヘッダーをクリックすることでソートできるが、任意に追加した was_published_today メソッドなどでは利用不可
  • デフォルトではカラムにメソッド名が表示されているが、short_description 属性にて変更できる

/mysite/polls/models.py

  1. class Poll(models.Model):
  2. :
  3. def was_published_today(self):
  4. return self.pub_date == datetime.date.today()
  5. # 以下を追加
  6. was_published_today.short_description = 'Published today?'

0367 django firstapp19.jpg

フィルターの追加

  1. class PollAdmin(admin.ModelAdmin):
  2. fieldsets = [
  3. (None , {'fields':['question']}),
  4. ('Date information', {'fields':['pub_date'],'classes':['collapse']}), ]
  5. inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_today')
  6. # 以下を追加
  7. list_filter = ['pub_date']

pub_date に対するフィルターサイドバーが表示される 0368 django firstapp20.jpg

検索フィールドの追加

以下を追加

  1. search_fields = ['question']

0369 django firstapp21.jpg

日付フィールドでのドリルダウン

以下を追加

  1. date_hierarchy = 'pub_date'

0370 django firstapp22.jpg

Admin のルック&フィールの変更

  • Djangoのテンプレートシステム機能によって、ルック&フィールを簡単に変更できる
  • mysite/settings.py 設定ファイルを開き、Djangoテンプレートの設定をTEMPLATE_DIRSで変更する
  • デフォルトで、TEMPLATE_DIRSは空になっている
  1. TEMPLATE_DIRS = (
  2. # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  3. # Always use forward slashes, even on Windows.
  4. # Don't forget to use absolute paths, not relative paths.
  5. "/home/my_username/mytemplates",
  6. )
  • TEMPLATE_DIRS で指定したフォルダの下に adminフォルダを作成し、/django/contrib/admin/templates/admin/base_site.html をコピーする
  1. # cd /usr/local/lib/python2.6/site-packages/django/contrib/admin/templates/admin
  2. # cp base_site.html /home/my_username/mytemplates/admin
  • コピーしたファイルを適当に変更
  1. {% load i18n %}
  2. {% load i18n %}
  3.  
  4. {% block title %}テンプレート:Title | {% trans 'My Sample site admin' %}{% endblock %}
  5.  
  6. {% block branding %}
  7. <h1 id="site-name">{% trans 'My Sample administration' %}</h1>
  8. {% endblock %}
  9.  
  10. {% block nav-global %}{% endblock %}
  • タイトルが変更された

0371 django firstapp23.jpg

[[Django 最初のアプリケーション 3]|[前|Django 最初のアプリケーション 1]]][[[次]]