6.博客首页开发(上)
首先实现首页开发,当用户点击我们的链接直接进入的首页。
- 设置路由
在主路由文件中加入代码,并在blog app下新建urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
]
~/blog/urls.py
from django.urls import path,re_path
from . import views
urlpatterns = [
path('',views.index_handler,name='blog_index')
]
- 设置视图函数
~/blog/views.py
from django.shortcuts import render
# Create your views here.
def index_handler(request):
return render(request, 'index.html')
- 配置静态文件,并在模板文件夹中加入index.html
关于静态文件配置详细说明,请移步Django中static(静态)文件详解以及{% static %}标签的使用,在本项目中,在根目录下创建static文件夹,并在html代码中修改文件路径,以达到预期显示效果。 - 博客首页展示所有博客并修改标签和最新文章
# ~/blog/views.py
from django.shortcuts import render
from .models import Blog, Tag
# Create your views here.
def index_handler(request):
context = {}
blog_list = Blog.objects.all().order_by('-createDatetime')
tags_list = Tag.objects.all()
context['blog_list'] = blog_list
context['tags_list'] = tags_list
# print(blog_list)
# print(tags_list)
return render(request, 'index.html', context=context)
- 讲道理写博客真的累…有人看我就续更吧。。。。。。