发布时间:2018-06-18 18:06:05编辑:admin阅读(5540)
1个Django 项目里面有多个APP目录大家共有一个 url容易造成混淆,于是路由分发让每个APP的拥有了自己单独的url
例如:将blog应用的url分离出来
1、进入mysite目录,修改urls.py文件
from django.contrib import admin
#分离路由,需要导入include方法
from django.urls import path,re_path,include
urlpatterns = [
path('admin/', admin.site.urls),
#注意include的是字符串形式的 文件路径
path('blog/', include('blog.blog_urls')),
]进入blog目录,创建文件blog_urls.py,内容如下:
from django.urls import path,re_path,include
from blog import views
urlpatterns = [
re_path('index/(\d+)/', views.index), # 分页
re_path('detail/(\d+)/', views.detail), # 详细信息
]2、业务处理函数代码 mysite/blog/views.py,内容如下:
from django.shortcuts import render,HttpResponse
# 临时存放一些数据,生产环境中,这些数据都是保存在数据库中
USER_LIST = []
for item in range(108):
temp = {"id": item, "username": "name"+str(item), "email": "email"+str(item)}
USER_LIST.append(temp)
def index(request, page):
# 将用户信息分页展示
# 第一页 0-9
# 第二页 10-19
# 第三页 20-29
page = int(page)
start_id = (page - 1) * 10
end_id = page * 10 -1
#用户列表
user_list = USER_LIST[start_id:end_id]
return render(request, "index.html", {"user_list": user_list})
def detail(request, nid):
# 用户ID的详细信息
nid = int(nid)
current_detail_dict = USER_LIST[nid]
return render(request, "detail.html", {"current_detail_dict": current_detail_dict})3、分页html代码 mysite/templates/index.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<thead>
<tr>
<td>ID</td>
<td>用户名</td>
<td>详细</td>
</tr>
</thead>
<tbody>
{% for item in user_list %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.username }}</td>
{#这里要加blog,否则点击之后,提示404#}
<td><a href="/blog/detail/{{ item.id }}/" target="_blank">查看详细</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>4、用户详细信息html代码 mysite/templates/detail.html,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li>{{ current_detail_dict.id }}</li>
<li>{{ current_detail_dict.username }}</li>
<li>{{ current_detail_dict.email }}</li>
</ul>
</body>
</html>5、目录结构
mysite/ ├── blog │ ├── admin.py │ ├── apps.py │ ├── blog_urls.py │ ├── __init__.py │ ├── models.py │ └── views.py ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── templates ├── detail.html └── index.html
6、访问用户信息分页url,点击页面查看详细
通过访问url
http://127.0.0.1:8000/blog/index/1/
最后的数字可以换成其他的

点击查看详细,就可以看到用户详细信息

上一篇: django URL (路由系统)
下一篇: python-web环境
51123
50517
41135
37978
32444
29345
28218
23060
23029
21352
1388°
2083°
1738°
1666°
1955°
1740°
2412°
4069°
3947°
2820°