Django トップページとindexの作成
初めに
前回に続いて本棚アプリケーションの作成を行いました。今回はトップページの作成と次回から使用するindexの作成を行いました。
これに対して行った具体的な手順をまとめます。
nissin-geppox.hatenablog.com
概要
- renderによるトップページの表示
- index.htmlの作成
概要
まず初めに、トップページを表示するためのindex_viewのルーティングを以下のように追加しました。
from django.urls import path from . import views urlpatterns = [ path('', views.index_view, name='index'), path('book/', views.ListBookView.as_view(), name='list-book'), path('book/<int:pk>/detail/', views.DetailBookView.as_view(), name='detail-book'), path('book/create/', views.CreateBookView.as_view(), name='create-book'), path('book/<int:pk>/delete/', views.DeleteBookView.as_view(), name='delete-book'), path('book/<int:pk>/update/', views.UpdateBookView.as_view(), name='update-book'), ]
次に、views.pyにindex_viewを以下のように定義しました。
-- 一部省略 -- class UpdateBookView(UpdateView): model = Book fields = ('title', 'text', 'category') template_name = 'book/book_update.html' success_url = reverse_lazy('list-book') def index_view(request): return render(request, 'book/index.html',{'somedata': 100})
続いて、以下のコマンドよりindex.htmlを作成しました。
$ touch book/templates/book/index.html
次に、上記で生成したindex.htmlに以下のコードを追加しました。
{{ somedata }}
最後に作成したトップページを表示しました。
上の画像より、somedataに紐づいたデータが表示されていることを確認することができました。
index.htmlの作成
続いて、具体的にindex.htmlの中身を作成していきます。
まず、views.pyを以下のように変更しました。
-- 一部省略 -- class UpdateBookView(UpdateView): model = Book fields = ('title', 'text', 'category') template_name = 'book/book_update.html' success_url = reverse_lazy('list-book') def index_view(request): object_list = Book.objects.all() return render(request, 'book/index.html',{'object_list': object_list})
続いて、index.htmlを以下のように変更しました。
{% extends 'base.html' %} {% block title %}書籍一覧{% endblock %} {% block h1 %}書籍一覧{% endblock %} {% block content %} {% for item in object_list %} <div class="p-4 m-4 bg-light border border-success rounded"> <h2 class="text-success">{{ item.title }}</h2> <h6>カテゴリ:{{ item.category }}</h6> <div class="mt-3"> <a href="{% url 'detail-book' item.pk %}">詳細へ</a> </div> </div> {% endfor %} {% endblock content %}
ここで、以下のコマンドを用いてサーバーを起動し、index.htmlにアクセスしました。
$ python3 manage.py runserver
以下の画像は表示された時の様子です。
上の画像より、index.htmlにより本の一覧が表示されることを確認することができました。
続いて、データを1つ追加し、もう一度トップページにアクセスしました。
以下の画像がその時の様子です。
上の画像より、正常にデータが追加されていることを確認することができました。
次に、表示されている3つのデータに対してカテゴリーごとに順番を並び替えるようにviews.pyを以下のように変更しました。
class UpdateBookView(UpdateView): model = Book fields = ('title', 'text', 'category') template_name = 'book/book_update.html' success_url = reverse_lazy('list-book') def index_view(request): object_list = Book.objects.order_by('category') return render(request, 'book/index.html',{'object_list': object_list})
この変更により、以下のように表示されました。
上の画像より、カテゴリー順にデータが並び替えられていることを確認することができました。