Django菜鸟实例教程:路由分组和路由转发器
文章列表模板
复制zdpdjango_basic,然后在templates中新建一个articles.html文件,用来展示文章列表:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文章列表:</h1>
<ul>
{% for article in articles %}
<li>{{ article.title }}</li>
{% empty %}
<li>暂无数据</li>
{% endfor %}
</ul>
</body>
</html>
创建视图函数
在index/views.py中,创建一个articles_view的视图函数:
from django.shortcuts import render
def article_view(request):
articles = [
{"id": i + 1, "title": f"文章标题{i + 1}"}
for i in range(10)
]
return render(request, "article.html", {"articles": articles})
修改路由
接着,修改index/urls.py,定义文章列表的路由:
from django.urls import path
from . import views
urlpatterns = [
path("articles/2024/4/", views.article_view),
]
此时,浏览器访问:http://localhost:8000/articles/2024/4/
使用正则路由分组
在实际的使用中,我们的年份和月份通常是根据实际的日期动态传递过来的,所以我们这里不能写死。
改写index/urls.py如下:
from django.urls import path, re_path
from . import views
urlpatterns = [
re_path("articles/(\d{4})/(\d{1,2})", views.article_view),
]
当捕获到数据以后,还需要在视图函数里面手动声明并接收。修改index/views.py如下:
from django.shortcuts import render
def article_view(request, year, month):
articles = [
{"id": i + 1, "title": f"文章标题{i + 1}", "date": f"{year}-{month}"}
for i in range(10)
]
return render(request, "article.html", {"articles": articles})
相应的,模板也稍加修改,将date字段渲染出来:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>文章列表:</h1>
<ul>
{% for article in articles %}
<li>{{ article.title }} {{ article.date }}</li>
{% empty %}
<li>暂无数据</li>
{% endfor %}
</ul>
</body>
</html>
具名分组
有名分组时按照关键字传参的,普通的正则分组则是使用位置传参。
我们可以将正则的分组取名。修改index/urls.py如下:
from django.urls import path, re_path
from . import views
urlpatterns = [
re_path("articles/(?P<year>\d{4})/(?P<month>\d{1,2})", views.article_view),
]
路由转发器
当正则表达式越来越复杂的时候,urls.py里面就会有很多看上去很臃肿的代码。
为了解决这个问题,Django给我们提供了路由转发器。
from django.urls import path, re_path
from . import views
from django.urls import register_converter
class YearConverter(object):
"""年份的路由转发器"""
regex = r"\d{4}"
def to_python(self, value):
return int(value)
class MonthConverter(object):
"""月份的路由转发器"""
regex = r"\d{1,2}"
def to_python(self, value):
return int(value)
register_converter(YearConverter, "year")
register_converter(MonthConverter, "month")
urlpatterns = [
path("articles/<year:year>/<month:month>/", views.article_view),
]
THE END