LoginSignup
1
1

More than 5 years have passed since last update.

Django チュートリアル: 地域図書館ウェブサイト (その2)

Last updated at Posted at 2019-03-15

こちらで作成したページの続きです。
Django チュートリアル: 地域図書館ウェブサイト
蔵書の一覧と、本の詳細ページを作成します。
Django Tutorial Part 6: Generic list and detail views の操作です。

1) catalog/urls.py の編集

catalog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('books/', views.BookListView.as_view(), name='books'), # 追加
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), # 追加
]

2) catalog/views.py の追加

catalog/views.py
from django.views import generic

class BookListView(generic.ListView):
    model = Book

class BookDetailView(generic.DetailView):
    model = Book

3) html の作成

catalog/templates/catalog/book_list.html
{% extends "catalog/base_generic.html" %}

{% block content %}
  <h1>Book List</h1>
  {% if book_list %}
  <ul>
    {% for book in book_list %}
      <li>
        <a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{book.author}})
      </li>
    {% endfor %}
  </ul>
  {% else %}
    <p>There are no books in the library.</p>
  {% endif %}       
{% endblock %}
catalog/templates/catalog/book_detail.html
{% extends "catalog/base_generic.html" %}

{% block content %}
  <h1>Title: {{ book.title }}</h1>

  <p><strong>Author:</strong> <a href="">{{ book.author }}</a></p> <!-- author detail link not yet defined -->
  <p><strong>Summary:</strong> {{ book.summary }}</p>
  <p><strong>ISBN:</strong> {{ book.isbn }}</p> 
  <p><strong>Language:</strong> {{ book.language }}</p>  
  <p><strong>Genre:</strong> {% for genre in book.genre.all %} {{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>  

  <div style="margin-left:20px;margin-top:20px">
    <h4>Copies</h4>

    {% for copy in book.bookinstance_set.all %}
      <hr>
      <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">{{ copy.get_status_display }}</p>
      {% if copy.status != 'a' %}
        <p><strong>Due to be returned:</strong> {{copy.due_back}}</p>
      {% endif %}
      <p><strong>Imprint:</strong> {{copy.imprint}}</p>
      <p class="text-muted"><strong>Id:</strong> {{copy.id}}</p>
    {% endfor %}
  </div>
{% endblock %}

4) catalog/templates/catalog/base_generic.html の修正

catalog/templates/catalog/base_generic.html
(省略)
<li><a href="{% url 'index' %}">Home</a></li>
<li><a href="{% url 'books' %}">All books</a></li>
<li><a href="">All authors</a></li>
(省略)

5) 開発サーバーを動かして http://127.0.0.1:8000/ にアクセス

一覧ページ
books_aa.png

詳細ページ
books_bb.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1