Skip to content

Djangoでウェブアプリを作る(10) – Django Admin の紹介

前回の記事:
Djangoでウェブアプリを作る(9)

今回参照する公式チュートリアル:
https://docs.djangoproject.com/ja/3.2/intro/tutorial02

前回は、Pythonシェルを使ってデータベースの操作を行ったが、Djangoには ” admin ” という管理画面がすでに存在おり、データベースを操作できるようになっているらしい。

スポンサードリンク

管理ユーザーを作成する

管理画面にログインする前に管理ユーザー用のアカウントを作成しておく必要がある。

以下のコマンドを実行。

python manage.py createsuperuser

アカウントデータを次のように入力した。

ユーザー名: ” admin ”
メールアドレス: ” admin@example.com ”
パスワード: ” 1234 “

c:\django_project\mysite>python manage.py createsuperuser
Username (leave blank to use 'username'): admin
Email address: admin@example.com
Password:
Password (again):

This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]:y

Superuser created successfully.
c:\django_project\mysite>

パスワードが簡単すぎたようだ。メッセージで警告された。さすがフルスタックフレームワーク。そこまで監視するんだ・・・

とりあえず、ユーザー作成ということで “y” を入力し実行。管理ユーザーアカウントが作成されたようだ。

開発サーバーの起動

runserverコマンドでサーバーを起動してみる。・・・OK

c:\django_project\mysite>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
August 24, 2021 - 19:55:00
Django version 3.2.6, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

” http://127.0.0.1:8000/admin/ ” で管理画面にアクセスできるようだ。

おお、ログイン画面が表示された。ここに先ほど設定したユーザー名とパスワードを入力。

ログインしたらこんな感じ。

Pollアプリをadmin上で編集できるようにする

確かにpollsアプリケーションは表示されてないな・・・

Question オブジェクトがadmin インタフェースを持つということを、adminに伝える必要があります。

何や、そこは自動でやってくれんのか・・・

polls/admin.py に以下を追記しなければならないようだ。

mysite/polls/admin.py

from django.contrib import admin
from .models import Question
admin.site.register(Question)

adminの機能を探究してみる

記述追加後、ブラウザをリロードすると「POLLS」の項目が表示された!

” Questions ” をクリック。最初に登録したデータが表示されている。

“What’s up?” をクリック。なるほど、ここでデータの内容を書き換えることができる・・ということか。

今日は、ここまで!

この記事をシェア

Comments are closed, but trackbacks and pingbacks are open.