如何实现电话簿详情页跳转及获取用户点击的PhoneBook?
解决电话簿详情页跳转与联系人展示问题
你现在的核心问题是没有传递点击的电话簿ID到详情页,同时URL路由、模板链接和视图逻辑三者没有对应上。我来一步步帮你修正:
1. 修改URL路由,添加电话簿ID参数
在urls.py中,detail路径需要接收电话簿的ID,这样视图才能识别用户点击的具体电话簿:
urlpatterns = [ path('', index, name="index"), path('create/', create_phone_book, name="create"), path('add/', add_to_phone_book, name="add"), path('view/', view_phone_book, name="view"), # 新增<int:phone_book_id>参数来接收电话簿ID path('detail/<int:phone_book_id>/', detailed_view_phone_book, name="detailed_view") ]
2. 更新详情视图,获取指定电话簿的联系人
在view.py中,detailed_view_phone_book函数需要接收phone_book_id参数,通过ID定位到目标电话簿,再过滤出关联的联系人:
def detailed_view_phone_book(request, phone_book_id): # 通过ID获取用户点击的电话簿对象 target_phone_book = PhoneBook.objects.get(id=phone_book_id) # 筛选属于该电话簿的所有联系人 all_contacts = Contact.objects.filter(phone_book=target_phone_book) context = { 'all_contacts': all_contacts } return render(request, "CallCenter/detailed_view_phone_book.html", context)
3. 修复首页模板的跳转链接
在view_phone_book.html里,不需要用form包裹a标签,直接用Django的{% url %}模板标签生成带ID的跳转链接即可:
<table> <tr> <th>Phone Book</th> </tr> {% for phone_book in all_phone_books %} <tr> <!-- 使用{% url %}标签生成指向详情页的链接,传递当前电话簿的ID --> <td><a href="{% url 'detailed_view' phone_book.id %}">{{ phone_book }}</a></td> </tr> {% endfor %} </table>
4. 修正详情页模板的循环变量
在detailed_view_phone_book.html中,上下文变量是all_contacts,但模板里误用了all_phone_detail,需要统一:
<table> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone Number</th> </tr> <!-- 把all_phone_detail替换为上下文里的all_contacts --> {% for phone_detail in all_contacts %} <tr> <td>{{ phone_detail.first_name }}</td> <td>{{ phone_detail.last_name }}</td> <td>{{ phone_detail.phone_number }}</td> </tr> {% endfor %} </table>
完成这些修改后,用户点击电话簿名称时,会自动跳转到对应ID的详情页,视图会根据ID加载该电话簿下的所有联系人并展示出来。
内容的提问来源于stack exchange,提问作者Ayodele Ashad




