视频连接:08.常用的模版标签和过滤器
继续搭建blog
blog/views.py
from django.shortcuts import render_to_response, get_object_or_404
from .models import Blog, BlogType
def blog_list(request):
context = {}
context['blogs'] = Blog.objects.all()
# context['blogs_count'] = Blog.objects.all().count()
return render_to_response('blog_list.html', context)
def blog_detail(request, blog_pk):
context = {}
context['blog'] = get_object_or_404(Blog, pk=blog_pk)
return render_to_response('blog_detail.html', context)
def blogs_with_type(request, blog_type_pk):
context = {}
blog_type = get_object_or_404(BlogType, pk=blog_type_pk)
context['blogs'] = Blog.objects.filter(blog_type=blog_type)
context['blog_type'] = blog_type
return render_to_response('blogs_with_type.html', context)
blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:blog_pk>', views.blog_detail, name='blog_detail'),
path('type/<int:blog_type_pk>', views.blogs_with_type, name='blogs_with_type',)
]
blog/templates/blog_detail.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ blog.title }}</title>
</head>
<body>
<div>
<a href="{% url 'home' %}">
<h3>个人博客网站</h3>
</a>
<hr>
</div>
<h3>{{ blog.title }}</h3>
<p>作者:{{ blog.author }}</p>
<p>发表日期:{{ blog.created_time|date:"Y-m-d" }}</p>
<p>分类:
<a href='{% url 'blogs_with_type' blog.blog_type.pk %}'>
{{ blog.blog_type }}
</a>
</p>
<p>{{ blog.content }}</p>
</body>
</html>
blog/templates/blog_list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的网站</title>
</head>
<body>
<div>
<a href="{% url 'home' %}">
<h3>个人博客网站</h3>
</a>
</div>
<hr>
{% for blog in blogs %}
<a href="{% url 'blog_detail' blog.pk %}">
<h3>{{ blog.title }}</h3>
</a>
<p>{{ blog.content|truncatechars:30 }}</p>
{% empty %}
<p>---暂无博文,敬请期待---</p>
{% endfor %}
<p>一共有{{ blogs|length }} 篇博文</p>
</body>
</html>
blog/templates/blogs_with_type.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ blog_type.type_name }}</title>
</head>
<body>
<div>
<a href="{% url 'home' %}">
<h3>个人博客网站</h3>
</a>
</div>
<hr>
<h3>{{ blog_type.type_name }}</h3>
{% for blog in blogs %}
<a href="{% url 'blog_detail' blog.pk %}">
<h3>{{ blog.title }}</h3>
</a>
<p>{{ blog.content|truncatechars:30 }}</p>
{# 这是注释 #}
{% empty %}
<p>---暂无博文,敬请期待---</p>
{% endfor %}
<p>一共有{{ blogs|length }} 篇博文</p>
</body>
</html>
mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from blog.views import blog_list
urlpatterns = [
path('', blog_list, name='home'),
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')),
]