想要在Book的明细页,加入foreign key的作者的外部超连结的话,依照以下步骤即可:
在catalog/urls.py的urlpatterns加入这段:增加author-detail的url mapping机制
#加入Author資料表的詳細資料網頁的url mapping
path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'),
在catalog/views.py的最下面加入这段:增加author-detail的server side取db资料的行为
class AuthorDetailView(generic.DetailView):
"""
Generic class-based detail view for an author.
"""
model = Author
新增这个档案/locallibrary/catalog/templates/catalog/author_detail.html,.html档内容如下:
{% extends "base_generic.html" %}
{% block content %}
<h1>Author: {{ author.first_name }}</h1>
<p><strong>first_name:</strong> {{author.first_name}}</p>
<p><strong>last_name:</strong> {{author.last_name}}</p>
<p><strong>date_of_birth:</strong> {{author.date_of_birth}}</p>
<p><strong>date_of_death:</strong> {{author.date_of_death}}</p>
<div style="margin-left:20px;margin-top:20px">
<h4>Author's Books</h4>
{% for book in author.book_set.all %}
<hr>
<p><strong>title:</strong> {{book.title}}</p>
<p><strong>summary:</strong>{{book.summary}}</p>
{% endfor %}
</div>
{% endblock %}
book_detail.html里面的一个author的超连结,原本是空的超连结,改成下面这样:
<p><strong>Author:</strong> <a href="{% url 'author-detail' book.author.pk %}">{{ book.author }}</a></p>
这样就可以正确显示了author_detail: 这篇大概是这样…