如果需要一个URL路径是年/月/日/slug 来定位某一篇blog的详情
编辑urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
...
path('////',
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 %}
{{ post.title }}
Published {{ post.publish }} by {{ post.author }}
{{ 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)