版本声明:转载请注明出处。未经允许,禁止商业用途。
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主页,点击一篇博文中的用户名