创建视图以显示列表
创建了两个视图,分别是post_list和post_detail
from django.shortcuts import render, get_object_or_404
#Create your views here.
from .models import Post
def post_list(request):
posts = Post.published.all()
return render(request, 'blog/post/list.html', {'posts': posts})
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)
return render(request,'blog/post/detail.html',{'post': post})
向视图添加url路径
url路径可将url映射到视图上,第二个路径是接受参数
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail')
]
另外,需要在主url路径中包含blog应用程序的url路径
path('blog/', include('blog.urls', namespace='blog')),
构建标准url
post_detail url针对Post对象构建标准url
1.向模型中添加get_absolute_url()方法
2.使用reverse(),通过对应的名称和参数构建url
3.使用get_absolute_url()即可链接到特定的帖子
def get_absolute_url(self):
return reverse('blog:post_detail',args=[self.publish.year,self.publish.month,self.publish.day,self.slug])
创建视图模板
1.创建相应的目录
2.base.html(模板)
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static "css/blog.css" %}">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar-content">
<h2>My blog</h2>
<p>This is my blog.</p>
</div>
</body>
</html>
3.list.html
% extends "blog/base.html" %}
{% block title %}My blog{% endblock %}
{% block content %}
<h1>My blog</h1>
{% 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 %}
{% endblock %}
4.detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Published{{ post.publish }}by{{ post.author }}
</p>
{{ post.body|linebreaks }}
{% endblock %}