Django入门博客小案例
Django 入门博客小案例 安装 pip install django==2.0 创建项目 django-admin startproject [demo 项目名称] 运行项目 python manage.py runserver 创建应用 python manage.py startapp [blog 应用名称] hello world blog/views.py from django.http import HttpResponse def hello_world(request): return HttpResponse("hello world") 新建 blog/urls.py from django.urls import path, include import blog.views urlpatterns = [ path('hello_world', blog.views.hello_world) ] demo/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')) ] demo/settings.py INSTALLED_APPS = [ ... 'blog.apps.BlogConfig' ] 运行项目python manage.py runserver访问http://127.0.0.1:8000/blog/hello_world看到效果 创建模型 blog/models.py from django.db import models # Create your models here. class Article(models.Model): # 文章ID article_id = models.AutoField(primary_key=True) # 文章标题 title = models.TextField() # 文章摘要 brief_content = models.TextField() # 文章内容 content = models.TextField() # 发布时间 publish_date = models.DateTimeField(auto_now=True) 执行模型迁移python manage.py makemigrations 运行迁到文件同步到数据库python manage.py migrate shell测试模型 执行python manage.py shell >>> from blog.models import Article >>> article = Article() >>> article.title = 'demo test' >>> article.brief_content = 'demo test' >>> article.content = 'test content' >>> article.save() # 查询 >>> all = Article.objects.all() >>> row = all[0] >>> print(row.title) Django Admin模块 创建超级管理员 执行 python manage.py createsuperuser Username (leave blank to use 'admin'): admin Email address: 123@qq.com Password: Password (again): Superuser created successfully. 运行项目 python manage.py runserver 访问 http://127.0.0.1:8000/admin 模型注册 blog/admin.py from .models import Article admin.site.register(Article) 刷新后台页面 后台模型显示标题 blog/models.py ... def __str__(self): return self.title 返回页面数据 blog/views.py def article_content(request): article = Article.objects.all()[0] title = article.title brief_content = article.brief_content content = article.content article_id = article.article_id publish_date = article.publish_date return_str = 'title: %s,beief_content: %s,content: %s,article_id: %s,publish_date: %s' % (title,brief_content,content,article_id,publish_date) return HttpResponse(return_str) blog/urls.py path('content', blog.views.article_content) 访问 http://127.0.0.1:8000/blog/content 创建静态页面 首页 新建文件blog/templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container page-header"> <h1>我的博客<small>--嘿嘿</small></h1> </div> <div class="container page-body"> <div class="row"> <div class="col-md-9" role="main"> <div class="body-main"> <div> <h2>测试1</h2> <p class="lead">测试测试上传测试测试测试</p> </div> <div> <h2>测试1</h2> <p class="lead">测试测试上传测试测试测试</p> </div> </div> </div> <div class="col-md-3" role="complementary"> <h2>最新文章</h2> <h4>测试测试上传测试测试测试</h4> <h4>测试测试上传测试测试测试</h4> <h4>测试测试上传测试测试测试</h4> </div> </div> </div> </body> </html> 详细页 新建文件blog/templates/detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container page-header"> <h1>文章标题</h1> </div> <div class="container page-body"> <p class="lead">文章内容</p> </div> </body> </html> 模板系统 变量 {{ 变量 }} for {% for x in list %},{% endfor%} if-else {% if true %},{% else %},{% endif %} 数据渲染静态页面 首页 blog/templates/blog/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container page-header"> <h1>我的博客<small>--嘿嘿</small></h1> </div> <div class="container page-body"> <div class="row"> <div class="col-md-9" role="main"> <div class="body-main"> {% for article in article_list %} <div> <h2><a href="/blog/detail/{{ article.article_id }}">{{ article.title }}</a></h2> <p class="lead">{{ article.brief_content }}</p> </div> {% endfor %} </div> </div> <div class="col-md-3" role="complementary"> <h2>最新文章</h2> {% for article in article_list %} <h4><a href="/blog/detail/{{ article.article_id }}">{{ article.title }}</a></h4> {% endfor %} </div> </div> </div> </body> </html> blog/views.py def get_index_page(request): all_article = Article.objects.all() return render(request, 'blog/index.html', { 'article_list':all_article }) blog/urls.py path('index', blog.views.get_index_page) 详细页 blog/templates/blog/detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container page-header"> <h1>{{ curr_article.title }}</h1> </div> <div class="container page-body"> {% for section in section_list %} <p class="lead">{{ section }}</p> {% endfor %} </div> </body> </html> blog/views.py def get_detail_page(request, article_id): all_article = Article.objects.all() curr_article = None for article in all_article: if article.article_id==article_id: curr_article = article break # 分割文章的段落 section_list = curr_article.content.split('\n') return render(request, 'blog/detail.html', { 'curr_article': curr_article, 'section_list': section_list }) blog/urls.py path('detail/<int:article_id>', blog.views.get_detail_page) 访问地址: http://127.0.0.1:8000/blog/detail/1 上下篇文章跳转 blog/views.py def get_detail_page(request, article_id): all_article = Article.objects.all() curr_article = None previous_index = 0 next_index = 0 previous_article = None next_article = None for index, article in enumerate(all_article): if index == 0: previous_index = 0 next_index = index + 1 elif index == len(all_article)-1: previous_index = index-1 next_index = index else: previous_index = index -1 next_index = index + 1 if article.article_id == article_id: curr_article = article previous_article = all_article[previous_index] next_article = all_article[next_index] break # 分割文章的段落 section_list = curr_article.content.split('\n') return render(request, 'blog/detail.html', { 'curr_article': curr_article, 'section_list': section_list, 'previous_article': previous_article, 'next_article': next_article }) blog/templates/blog/detail.html .... <nav aria-label="..."> <ul class="pager"> <li class="previous"><a href="/blog/detail/{{ previous_article.article_id }}"><span aria-hidden="true">←</span> 上一篇:{{ previous_article.title }}</a></li> <li class="next"><a href="/blog/detail/{{ next_article.article_id }}">下一篇:{{ next_article.title }} <span aria-hidden="true">→</span></a></li> </ul> </nav> </body> 首页分页 blog/templates/blog/index.html ... <div class="body-footer"> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="/blog/index?page={{ previous_page }}" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {% for num in page_num %} <li><a href="/blog/index?page={{ num }}">{{ num }}</a></li> {% endfor %} <li> <a href="/blog/index?page={{ next_page }}" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> blog/views.py from django.core.paginator import Paginator def get_index_page(request): page = request.GET.get('page') if page: page = int(page) else: page = 1 all_article = Article.objects.all() paginator = Paginator(all_article, 1) page_num = paginator.num_pages page_article_list = paginator.page(page) if page_article_list.has_next(): next_page = page + 1 else: next_page = page if page_article_list.has_previous(): previous_page = page - 1 else: previous_page = page return render(request, 'blog/index.html', { 'article_list': page_article_list, 'page_num': range(1, page_num + 1), 'page': page, 'next_page': next_page, 'previous_page': previous_page }) 最新5篇文章 blog/views.py def get_index_page(request): page = request.GET.get('page') if page: page = int(page) else: page = 1 all_article = Article.objects.all() paginator = Paginator(all_article, 1) page_num = paginator.num_pages page_article_list = paginator.page(page) if page_article_list.has_next(): next_page = page + 1 else: next_page = page if page_article_list.has_previous(): previous_page = page - 1 else: previous_page = page # 最新5篇文章 top5_article_list = Article.objects.order_by('-publish_date')[:5] return render(request, 'blog/index.html', { 'article_list': page_article_list, 'page_num': range(1, page_num + 1), 'page': page, 'next_page': next_page, 'previous_page': previous_page, 'top5_article_list': top5_article_list }) blog/templates/blog/index.html <h2>最新文章</h2> {% for article in top5_article_list %} <h4><a href="/blog/detail/{{ article.article_id }}">{{ article.title }}</a></h4> {% endfor %}