LoginSignup
0
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-03-15

こちらで作成したページの続きです。
Django チュートリアル: 地域図書館ウェブサイト (その2)

作者の一覧と、作者の詳細ページを作成します。

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'),
    path('authors/', views.AuthorListView.as_view(), name='authors'), # 追加
    path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detai
l'), # 追加
]

2) catalog/views.py の追加

catalog/views.py
省略
class AuthorListView(generic.ListView):
    model = Author

class AuthorDetailView(generic.DetailView):
    model = Author

3) html の作成

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

{% block content %}
  <h1>Author List</h1>
  {% if author_list %}
  <ul>
    {% for author in author_list %}
      <li>
        <a href="{{ author.get_absolute_url }}">
    {{ author.last_name }} {{author.first_name}}</a>
      </li>
    {% endfor %}
  </ul>
  {% else %}
    <p>There are no authors in the library.</p>
  {% endif %}       
{% endblock %}
catalog/templates/catalog/author_detail.html
{% extends "catalog/base_generic.html" %}

{% block content %}
  <h1>Title: {{ author.last_name }} {{ author.first_name }}</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>Last Name:</strong> {{ author.last_name }}</p> 
  <p><strong>First Name:</strong> {{ author.first_name }}</p>  
  <p>生年月日: {{ author.date_of_birth }}</p> 
  <p>没年月日: {{ author.date_of_death }}</p> 

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

  </div>
{% endblock %}

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

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

5) catalog/templates/catalog/book_detail.html の修正

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

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

  <p><strong>Author:</strong> <a href="{% url 'author-detail' book.author.pk %}"
>{{ book.author }}</a></p>
(省略)

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

作者の一覧
author_aa.png

作者の詳細
author_bb.png

本の詳細のページから、作者の詳細にリンク
author_cc.png

0
0
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
0
0