版本聲明:轉載請註明出處。未經允許,禁止商業用途。
12 使用Python Django開發web應用 處理URL中的參數 講師:劉一凡
查詢指定用戶的blog,演示帶參數的url。
點擊blog頁面中的用戶名,可以查看這個用戶的blog。
第一步:
blog/urls.py添加url
path('userblog/',views.userblog),
第二步:
定義view函數
def userblog(request):
#從URL中提取參數
username=request.GET.get("username")
blogs=Blog.objects.filter(username=username)
return render(request,'userblog.html',{'blogs':blogs})
第三步:
修改主頁模板的username爲鏈接
<p><a href="/blog/userblog/?username={{ blog.username }}">{{ blog.username }}</a></p>
第四步:
增加一個新的template userblog.html用於顯示指定用戶的blog。我們直接從blog.html中摘取一部分
<html lang="zh-CN">
<head>
</head>
<body>
{% if blogs %}
{% for blog in blogs %}
<h2>{{ blog.head }}</h2>
<p>{{ blog.timestamp }}</p>
<p>{{ blog.content }}</p>
<p>{{ blog.username }}</p>
{% endfor %}
{% else %}
<p>Nothing!</p>
{% endif %}
</body>
</html>
第五步:
打開blog主頁,點擊一篇博文中的用戶名