Django
中文官网:初识 Django | Django 文档 | Django (djangoproject.com)
Django 是一个由 Python 编写的一个开放源代码的 Web 应用框架。
使用 Django,只要很少的代码,Python 的程序开发人员就可以轻松地完成一个正式网站所需要的大部分内容,并进一步开发出全功能的 Web 服务 Django 本身基于 MVC 模型,即 Model(模型)+ View(视图)+ Controller(控制器)设计模式,MVC 模式使后续对程序的修改和扩展简化,并且使程序某一部分的重复利用成为可能。
MVC 优势:
- 低耦合
- 开发快捷
- 部署方便
- 可重用性高
- 维护成本低
- …
Python 加 Django 是快速开发、设计、部署网站的最佳组合。
特点
- 强大的数据库功能
- 自带强大的后台功能
- 优雅的网址
安装教程
参考:(19条消息) django安装教程_哇咔君i的博客-CSDN博客_django安装
命令
常用命令:
新建项目
django-admin startproject HelloWorld
新建应用
python manage.py startapp blog
启动
python manage.py runserver
第一个应用helloWorld
blog/vews.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello_word(request):
return HttpResponse("Hello World")
blog/urls.py
from django.urls import path , include
import blog.views
urlpatterns =[
path('hello_world',blog.views.hello_word)
]
HelloWorld/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('^', admin.site.urls),
path('blog/', include('blog.urls'))
]
HelloWorld/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#myapp 配置
'blog.apps.BlogConfig
]
运行访问 ip:端口/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
打开django shell 添加文章
命令行
python manage.py shell
引入依赖
from blog.modles import Article
实例化
a = Article()
赋值
a.title = "xxx"
保存到数据库
a.save()
从数据库取出所有数据
articles = Article.objects.all()
打印输出
print(ax.title)
打开后台管理来添加文章
创建超级管理员
python manage.py createsuperuser
把模型交给后台管理
blog/admin.py
from django.contrib import admin
# Register your models here.
from .models import Article
admin.site.register(Article)
浏览器打开 ip:端口/admin
获取文章数据并展示
blog/views.py
from django.shortcuts import render
from django.http import HttpResponse
from blog.models import Article
# Create your views here.
def hello_word(request):
return HttpResponse("Hello World")
def content(request):
articles = Article.objects.all()
a = articles[0]
title = a.title
brief_content = a.brief_content
content = a.content
publish_date = a.publish_date
return HttpResponse('title:%s,brief_content:%s,' \
'content:%s,publish_date:%s'%(title,brief_content,content,publish_date))
blog/urls.py
from django.urls import path , include
import blog.views
urlpatterns =[
path('hello_world',blog.views.hello_word),
path('content',blog.views.content)
]
访问 ip:端口/blog/content
使用Django模板引擎
blog中创建templates目录
新建blog目录
新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
<h1>Django 文章
<small>————DingDingDing</small>
</h1>
</div>
<div class="container page-body">
<div class="col-md-9" role="main">
{% for article in article_list %}
<div>
<h2>{{article.title}}</h2>
<p>{{article.content}}</p>
</div>
{% endfor %}
</div>
<div class="col-md-3" role="complementary">
<div>
<h2>最新文章</h2>
{% for article in article_list %}
<h4><a>{{article.title}}</a></h4>
{% endfor %}
</div>
</div>
</div>
</body>
</html>
blog/views.py启用引擎
def get_articles(request):
articles = Article.objects.all()
return render(request, 'blog/index.html',
{
'article_list': articles
})
blog/urls.py 配置路由
from django.urls import path , include
import blog.views
urlpatterns =[
path('hello_world',blog.views.hello_word),
path('content',blog.views.content),
path('index',blog.views.get_articles)
]
访问端口:IP:端口 /blog/index
新建detail.html做详情页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章详情</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
<h1>{{article.title}}</h1>
</div>
<div class="container page-body">
<div class="col-md-9" role="main">
{% for page in pages %}
<div>
<p>{{page}}</p>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
blog/urls.py 设置路由
from django.urls import path , include
import blog.views
urlpatterns =[
path('hello_world',blog.views.hello_word),
path('content',blog.views.content),
path('index',blog.views.get_articles),
path('detail',blog.views.get_detail)
]
blog/views.py 配置引擎
def get_detail(request):
article = Article.objects.all()[0]
pages = article.content.split('\n')
return render(request, 'blog/detail.html',
{
'article': article,
'pages':pages
})
首页跳转详情页
blog/views.py修改引擎
def get_detail(request,article_id):
article = Article.objects.all()
curr_article = None
for a in article:
if a.article_id==article_id:
curr_article = a
break
pages = curr_article.content.split('\n')
return render(request, 'blog/detail.html',
{
'article': curr_article,
'pages':pages
})
blog/urls.py修改
urlpatterns =[
path('hello_world',blog.views.hello_word),
path('content',blog.views.content),
path('index',blog.views.get_articles),
# path('detail',blog.views.get_detail),
path('detail/<int:article_id>',blog.views.get_detail)
]
详情页上下篇切
blog/views.py改造
def get_detail(request,article_id):
articles = Article.objects.all()
curr_article = None
pre_article = None
next_article = None
for index,a in enumerate(articles):
if index ==0:
pre_index=index
next_index=index+1
elif index==len(articles)-1:
pre_index = index-1
next_index = index
else:
pre_index = index-1
next_index = index+1
if a.article_id==article_id:
curr_article = a
pre_article = articles[pre_index]
next_article = articles[next_index]
break
pages = curr_article.content.split('\n')
return render(request, 'blog/detail.html',
{
'article': curr_article,
'pages':pages,
'pre_article':pre_article,
'next_article':next_article,
})
detail.html改造
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文章详情</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
<h1>{{article.title}}</h1>
</div>
<div class="container page-body">
<div class="col-md-9" role="main">
{% for page in pages %}
<div>
<p>{{page}}</p>
</div>
{% endfor %}
</div>
</div>
<div>
<nav aria-label="...">
<ul class="pager">
<li><a href="/blog/detail/{{pre_article.article_id}}">上一篇:{{pre_article.title}}</a></li>
<li><a href="/blog/detail/{{next_article.article_id}}">下一篇:{{next_article.title}}</a></li>
</ul>
</nav>
</div>
</body>
</html>
首页分页
blog/views.py改造
from django.core.paginator import Paginator
def get_articles(request):
page = request.GET.get('page')
if page:
page = int(page)
else:
page = 1
print("page:", page)
articles = Article.objects.all()
paginator = Paginator(articles, 1)
page_num = paginator.num_pages
page_article_list = paginator.page(page)
next_page = None
pre_page =None
if page_article_list.has_next():
next_page = page+1
else:
next_page = page
if page_article_list.has_previous:
pre_page = page-1
else:
pre_page = page
return render(request, 'blog/index.html',
{
'article_list': page_article_list,
'page_num': range(1, page_num + 1),
'curr_page': page,
'next_page': next_page,
'pre_page': pre_page
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Django</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
crossorigin="anonymous"></script>
</head>
<body>
<div class="container page-header">
<h1>Django 文章
<small>————DingDingDing</small>
</h1>
</div>
<div class="container page-body">
<div class="col-md-9" role="main">
{% for article in article_list %}
<div>
<h2><a href="/blog/detail/{{article.article_id}}">{{article.title}}</a></h2>
<p>{{article.brief_content}}</p>
</div>
{% endfor %}
<div class="body-footer">
<div class="col-md-4 col-md-offset-3">
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="/blog/index?page={{next_page}}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% for page in page_num %}
<li><a href="/blog/index?page={{page}}">{{page}}</a></li>
{% endfor %}
<li>
<a href="/blog/index?page={{pre_page}}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="col-md-3" role="complementary">
<div>
<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>
排序
def get_articles(request):
page = request.GET.get('page')
if page:
page = int(page)
else:
page = 1
print("page:", page)
articles = Article.objects.all()
paginator = Paginator(articles, 1)
page_num = paginator.num_pages
page_article_list = paginator.page(page)
#-------------------------start
top5_article = Article.objects.order_by('-publish_date')[:5]
# top5_article = Article.objects.order_by('publish_date')[:5] 正序
next_page = None
pre_page =None
if page_article_list.has_next():
next_page = page+1
else:
next_page = page
if page_article_list.has_previous:
pre_page = page-1
else:
pre_page = page
return render(request, 'blog/index.html',
{
'article_list': page_article_list,
'page_num': range(1, page_num + 1),
'curr_page': page,
'next_page': next_page,
'pre_page': pre_page,
'top5_article':top5_article
})