首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Django的路由分组和路由转发器

02 查询文章信息

文章列表模板

复制zdpdjango_basic,然后在templates中新建一个articles.html文件,用来展示文章列表:

<meta charset="UTF-8">

<title>Title</title>

{% for article in articles %}

<li>{{ article.title }}</li>

{% empty %}

<li>暂无数据</li>

{% endfor %}

创建视图函数

在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字段渲染出来:

<meta charset="UTF-8">

<title>Title</title>

{% for article in articles %}

<li>{{ article.title }}  {{ article.date }}</li>

{% empty %}

<li>暂无数据</li>

{% endfor %}

具名分组

有名分组时按照关键字传参的,普通的正则分组则是使用位置传参。

我们可以将正则的分组取名。修改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),

]

  • 发表于:
  • 原文链接https://page.om.qq.com/page/Oxo4N6tVCS5STGHwRCjH9aHw0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券