Django企业开发实战-blog项目(6)

本文介绍了在Django中开发面向用户的界面,包括博客列表页、文章详情页和友链视图的实现。通过优化View,重构post_list视图,减少了数据库请求,并展示了如何配置侧边栏,提升用户体验。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值