一、环境安装
python环境安装
https://www.python.org/ftp/python/3.8.3/python-3.8.3.exe
安装完成后 运行python命令
conda安装 https://www.anaconda.com/products/individual
Django安装: cmd 命令:
pip install django==2.0
安装完成后 运行命令: django-admin查看安装是否完成
二、初识Django项目
Django基本命令: django-admin 可查看基本命令
- startproject 创建一个Django项目:
- startapp 创建一个Django应用
- check 校验项目完整性
- runserver 本地简易运行Django项目
- shell 进入Django项目的python shell环境
- test 执行Django 用例测试
- makemigrations 创建模型变更的迁移文件
- migrate 执行上一个命令创建的迁移文件
- dumpdata 把数据库数据导出到文件
- loaddata 把文件数据导入到数据库
项目目录介绍
创建项目运行命令 : django-admin startproject projectname
创建项目成功后的项目结构:
- settings.py : 项目配置文件
- urls.py : 项目路由配置文件
- manage.py : 项目管理文件
Django 应用 VS Django 项目
每个应用可以自己管理模型、视图、模板、路由、静态文件等; 一个Django项目包含一组配置和若干个Django应用。
在Django项目中创建Django应用
在Terminal中运行命令:python manage.py startapp blog
应用目录介绍
- views.py 视图处理的地方
- models.py 定义应用模型的地方
- admin.py 定义Admin模块管理对象的地方
- apps.py 声明应用的地方
- tests.py 编写应用测试用例的地方
- urls.py (自己创建的) 管理应用路由的地方
Django Hello world
编辑应用中的views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def hello_world(request):
return HttpResponse("hello World")
编辑应用中的 urls.py
from django.urls import path,include
import blog.views
urlpatterns = [
path('hello_world',blog.views.hello_world)
]
编辑项目的 urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("blog/",include('blog.urls')) //应用的路由
]
编辑项目的 settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 新增应用的配置
'blog.apps.BlogConfig'
]
启动项目:
浏览器访问: http://127.0.0.1:8000/blog/hello_world
执行原理:
三、初识Django模型层
- 模型层是什么: 位于Django视图层和数据库之间
- 为什么需要模型层: 屏蔽不同数据库之间的差异;使开发者更加专注于业务逻辑的开发;提供很多便捷工具有助开发;
- 模型层的相关配置:
创建博客文章模型
编辑应用的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 = models.TextField()
# 文章的主要内容
content = models.TextField()
# 文章的发布日期
publish_date = models.DateTimeField(auto_now=True)
创建迁移文件:python manage.py makemigrations
执行迁移文件:python manage.py migrate
Django Shell
- Django shell 是什么? 用于交互式的python编程
- 为什么需要Django Shell ? 临时性操作使用Django Shell更加方便;小范围debug更简单,不需要运行整个项目来测试。
- 使用Django shell新建一篇文章: 在Idea Terminal 中运行
D:\JavaWorkspace\IdeaSpace\django_demo>python manage.py shell Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from blog.models import Article In [2]: a = Article() In [3]: a.title = 'Test Shell' In [4]: a.brief = 'Test Shell, brief' In [5]: a.content = 'Test Shell, New Article, Main Content...' In [6]: print(a) Article object (None) In [7]: a.save() In [8]: articles = Article.objects.all(); In [9]: article = articles[0] In [10]: print(article.title) Test Shell In [11]: print(article.content) Test Shell, New Article, Main Content...
Django Admin 模块是什么
- Django 的后台管理工具
- 读取定义的模型元数据,提供强大的管理使用页面
为什么需要 Django Admin模块?
- 使用Django Shell 新增文章太复杂了
- 管理页面是基础设施中重要的部分
- 认证用户、显示管理模型、检验输入等功能
Django Admin模块的使用
- 创建管理员用户
- 登录页面管理
D:\JavaWorkspace\IdeaSpace\django_demo>python manage.py createsuperuser
Username (leave blank to use 'lyx05'): admin
Email address:
Password:
Password (again):
Superuser created successfully.
引用模型注册到admin : 编辑 应用中的admin.py
from django.contrib import admin
# Register your models here.
from .models import Article
admin.site.register(Article)
启动项目,访问登录页面,输入刚才添加的用户密码登录。
进入Article, 可进行增删查改操作;
由于默认显示的object(1) 这样的数据,无法分辨数据,可以自定义显示: 编辑 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 = models.TextField()
# 文章的主要内容
content = models.TextField()
# 文章的发布日期
publish_date = models.DateTimeField(auto_now=True)
# 显示标题
def __str__(self):
return self.title
实现博客数据返回页面
修改应用的views.py 新增以下代码
from blog.models import Article
def article_content(request):
article = Article.objects.all()[0]
article_id = article.article_id
title = article.title
brief = article.brief
content = article.content
publish_date = article.publish_date
return_str = 'ID:%s,title:%s,brief:%s,content:%s,publish_date:%s' % (article_id,title,brief,content,publish_date)
return HttpResponse(return_str)
配置应用路由:urls.py, 增加路由
path('content',blog.views.article_content)
浏览器访问 content 地址
四、Django视图与模板
Django 模板
- 模板系统的表现形式是文本
- 分离文档的表现形式和表现内容
- 模板系统定义了特有的标签占位符
基本语法
- 变量标签:{{ 变量 }}
<p>Dear {{ person_name }},</p>
- for循环标签: {% for x in list %}, {% endfor %}
<ul> {% for item in item_list %} <li>{{ item }}</li> {% endfor %} </ul>
- if-else 分支标签: {% if %},{% else %},{% endif %}
{% if ordered_warranty %} <p>Your warranty information will be included in the packaging.</p> {% else %} <p>You didn't order a warranty, so you're on your own when the products inevitably stop working.</p> {% endif %}
在引用blog下新建文件夹 templates/blog ,在blog文件夹下新建index.html , 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>三小时入门Django Web框架
<small> —— by LYX</small>
</h1>
</div>
<div class="container page-body">
<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>
{{article.brief}}
</p>
</div>
{% endfor %}
</div>
<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={{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>
</div>
</div>
<div class="col-md-3" role="complementary">
<div>
<h2>最新文章</h2>
{% for article in top10_article_list %}
<h4><a href="/blog/detail/{{article.article_id}}">{{ article.title }}</a></h4>
{% endfor %}
</div>
</div>
</div>
</body>
</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 body-main">
<div>
{% for section in section_list %}
<p>{{ section }}</p>
{% endfor %}
</div>
</div>
<div>
<nav aria-label="...">
<ul class="pager">
<li><a href="/blog/detail/{{ previous_article.article_id }}">上一篇:{{ previous_article.title }}</a></li>
<li><a href="/blog/detail/{{ next_article.article_id }}">下一篇:{{ next_article.title }}</a></li>
</ul>
</nav>
</div>
</body>
</html>
编辑 应用的 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()
top10_article_list = Article.objects.order_by('-publish_date')[:10]
paginator = Paginator(all_article, 6)
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': all_article,'page_num':range(1,page_num + 1), 'curr_page':page,'next_page':next_page,'previous_page':previous_page,'top10_article_list':top10_article_list})
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})
配置urls.py
urlpatterns = [
path('hello_world',blog.views.hello_world),
path('content',blog.views.article_content),
path('index',blog.views.get_index_page),
path('detail/<int:article_id>',blog.views.get_detail_page)
]
启动项目:
至此, 使用 Django 创建一个web博客已完成。