Django用日期URL定位详情

如果需要一个URL路径是年/月/日/slug 来定位某一篇blog的详情

编辑urls.py

from django.urls import path
from . import views

app_name = 'blog'
urlpatterns = [

    ...
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',
        views.post_detail,
        name='post_detail'),

]

编辑models.py文件并添加一个get_absolute_url()方法来构建url并传递可选参数。

from django.urls import reverse

...

class Post(models.Model):

    ...
    
    def get_absolute_url(self):
        return reverse(
            "blog:post_detail",
            args=[
                self.publish.year,
                self.publish.month,
                self.publish.day,
                self.slug
            ]
        )  
    ...

在post/list.html模板中使用get_absolute_url()方法来链接到特定的帖子。
 

...
{% for post in posts %}
    <h2>
        <a href="{{ post.get_absolute_url }}">
        {{ post.title }}
        </a>
    </h2>
    <p class="date">
        Published {{ post.publish }} by {{ post.author }}
    </p>
        {{ post.body|truncatewords:30|linebreaks }}
{% endfor %}
...

view通过路径传参,使用年,月,日和slug定位blog

def post_detail(request,year,month,day,post):

    post = get_object_or_404(Post,slug=post,
                             status='published',
                             publish__year=year,
                             publish__month=month,
                             publish__day=day
                             )

    template = "blog/post/detail.html"
    context = {
        "post":post,
    }

    return render(request,template,context)




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值