<< home

Django入門

Djangoレクチャー2

index表示

  1. バージョン確認: $ python -m django --version
  2. プロジェクト作成:
    $ mkdir djangotutorial $ django-admin startproject mysite djangotutorial $ python manage.py runserver
  3. アプリ登録
    $ python manage.py startapp polls
  4. ビュー作成
    from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.")
  5. URLconfを定義
    • polls/urls.py
      from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ]
  6. mysiteのURLconfの設定
    • mysite/urls.py
      from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ]
      python manage.py runserver

データベース

  1. INSTALLED_APPSの初期構成
    django.contrib.admin - 管理(admin)サイト。まもなく使います django.contrib.auth - 認証システム django.contrib.contenttypes - コンテンツタイプフレームワーク django.contrib.sessions - セッションフレームワーク django.contrib.messages - メッセージフレームワーク django.contrib.staticfiles - 静的ファイルの管理フレームワーク
  2. データベースにテーブルを作成する(テスト)
    python manage.py migrate
  3. モデルの定義
    • polls/models.py
      from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
  4. appの登録
    "polls.apps.PollsConfig",<-追加 "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles",
    "polls.apps.PollsConfig" と記述する場合: アプリケーションの設定クラスを指定します。 設定クラス内でカスタマイズされた設定が適用されます。 アプリケーションの初期化時に特定の処理を実行することができます。 "polls" と記述する場合: アプリケーションの名前を直接指定します。 デフォルトの設定クラスが適用されます。 特にカスタマイズが必要ない場合に使用されます。
  5. 管理画面の登録
    • polls/admin.py
      from django.contrib import admin from .models import Question,Choice admin.site.register(Question) admin.site.register(Choice)
  6. マイグレーションの実行
    python manage.py makemigrations polls python manage.py migrate
  7. スーパーユーザーの登録
    python manage.py createsuperuser
  8. テンプレートの導入
    • mysite/settings.py
      ~ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ~
      import os ~ TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ~
  9. テンプレートの作成
    • templates/polls/index.html
      <p>No polls are available.</p>
  10. views.pyの変更
    • polls/views.py
      from django.http import HttpResponse from django.shortcuts import render from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by("-pub_date")[:5] context = {"latest_question_list": latest_question_list} return render(request, "polls/index.html", context) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id)
  11. 質問
    from django.http import HttpResponse,Http404 from django.shortcuts import render from .models import Question def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, "polls/detail.html", {"question": question})
  12. URLconfの変更
    • polls/urls.py
      from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path("", views.index, name="index"), # ex: /polls/5/ path("<int:question_id>/", views.detail, name="detail"), # ex: /polls/5/results/ path("<int:question_id>/results/", views.results, name="results"), # ex: /polls/5/vote/ path("<int:question_id>/vote/", views.vote, name="vote"), ]
  13. 質問用テンプレート
    • templates/polls/detail.html
      <h1></h1> <ul> </ul>
  14. ショートカット:get_object_or_404()
    from django.shortcuts import get_object_or_404, render from .models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, "polls/detail.html", {"question": question})
<< home