[Python+Django]初心者筆記8(從資料明細頁做foreign key外部超連結)

[Python+Django]初心者筆記8(從資料明細頁做foreign key外部超連結)

想要在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:

這篇大概是這樣…


參考資料:
Django Tutorial Part 6: Generic list and detail views
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views