github链接 https://github.com/yt-xy/Django-blog
开发面向用户的界面
先思考,页面的大致布局
列表页View:根据不同的查询条件分别展示博客首页、分类列表和标签列表页
文章页View:展示博文详情页
友链View:展示所有友情链接
blog/urls.py
from django.conf.urls import url
from django.contrib import admin
from blog.custom_site import custom_site
from blogs.views import post_list, post_detail
from config.views import links
urlpatterns = [
# path('admin/', admin.site.urls),
url(r'^super_admin/', admin.site.urls),
url(r'^admin/', custom_site.urls),
url(r'^$', post_list),
url(r'^category/(?P<category_id>\d+)/$', post_list),
url(r'^tag/(?P<tag_id>\d+)/$', post_list),
url(r'^post/(?P<post_id>\d+).html$', post_detail),
url(r'^links/$', links),
]
我们可以将URL的定义理解为是一个路径(正则字符串)对应一个函数的映射,比如url(r'^$', post_list)
意味着如果用户访问博客首页,就把请求传递到post_list这个函数中。
完整的URL参数:url(<正则或者字符串>, <view function>, <固定参数 context>, <url的名称>)
先编写简单的View代码
blogs/views.py
from django.http import HttpResponse
def post_list(request, category_id=None, tag_id=None):
content = 'post_list category_id={category_id}, tag_id={tag_id}'.format(
category_id=category_id,
tag_id=tag_id,
)
return HttpResponse(content)
def post_detail(request, post_id):
return HttpResponse('detail')
config/views.py
from django.http import HttpResponse
def links(request):
return HttpResponse('links')
再进行一点简单优化
blogs/views.py
from django.shortcuts import render
def post_list(request, category_id=None, tag_id=None):
return render(request, 'blog/list.html', context={
'name': 'post_list'})
def post_detail(request, post_id):
# return HttpResponse('detail')
return render(request, 'blog/detail.html', context={
'name': 'post_detail'})
render方法,接受参数为:render(request, template_name, context=None, status=None, using=None)
request:封装了HTTP请求的request对象
template_name:模板名称,可以像前面的代码那样带上路径
context:字典数据,它会传递到模板中
content_type:页面编码类型,默认值是text/html
status:状态码,默认值是200
using:使用哪种模板引擎解析
新建模板文件
blog/templates/blogs/list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>blog 博客系统</title>
</head>
<body>
<h1>list</h1>
{
{ name }}
</body