Django是一个开放源代码的Web应用框架,由Python写成。采用了MVC的框架模式,即模型M,视图V和控制器C。它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的,便是CMS(内容管理系统)软件。并于2005年7月在BSD许可证下发布。这套框架是以比利时的吉普赛爵士吉他手Django Reinhardt来命名的。css
版本:1.8.三、1.11.x (推荐)、2.xhtml
官网下载地址:https://www.djangoproject.com/download/python
pip3 install django==1.11.11 安装
pip3 install django==1.11 -i https://pypi.tuna.tsinghua.edu.cn/simple 指定安装源
pip3 uninstall django 卸载
pip3 list 查看当前Python解释器安装了哪些第三方包
django-admin startproject s21django
在当前目录下建立一个名为 s21django 的Django项目 mysql
第一步:选择File>>New Project;web
第二步:选择Django,点击Create;正则表达式
第三步:选择在新的窗口中打开,点击ok;sql
建立完成后目录结构:数据库
#目录结构介绍 mysite/ ├── manage.py # 管理文件 └── mysite # 项目目录 ├── __init__.py ├── settings.py # 配置 ├── urls.py # 路由 --> URL和函数的对应关系 └── wsgi.py # runserver命令就使用wsgiref模块作简单的web server
启动Django项目:django
更改端口:编程
index文件内容以下:
urls.py文件内容以下:
views.py文件内容以下:
settings.py文件内容以下:
""" Django settings for mysite2 project. Generated by 'django-admin startproject' using Django 1.11.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # BASE_DIR是我当前Django项目的根目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'vj5z&5kl+%sk@a%rbfl=z*&!(6amfme758_cw6ke6&ymv=^gyq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition # 当前Django项目按照的app都有哪一些 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', #'app02' # 简便写法 将咱们建立的app02在Django项目注册一下 ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite2.urls' # 全部和html文件相关的配置 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Django项目中用到的html文件要去哪里找 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite2.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
1)PyCharm里面启动:
点绿色的小三角
2)命令行启动
a. 切换到项目目录下!
b. python manage.py runserver
python manage.py runserver 127.0.0.1:8090
python manage.py runserver 8091
1) 在PyCharm建立,只能在开始建立项目的时候建立一次,以后再建立须要在命令行建立。
2)在命令行建立
a. 切换到项目目录下!
b. python manage.py startapp app名字
c. 在settings.py里面注册你新建立的那个app
1. request.method --> 获取用户请求的方法
- GET --> 表示用户向我要一个页面这种操做
- POST --> 表示用户向我发送一些数据
2. request获取URL中的参数
/xx/?name=alex&age=9000
request.GET --> 大字典
- request.GET['name'] --> 不推荐 取不到值会报错
- request.GET.get("name","") --> 推荐 能够设置默认值
3. request.POST --> 一个大字典,存的是用户post发过来的数据
1. request.POST['key'] --> 不推荐
2. request.POST.get('key', '默认值')
1. 基础必会三件套
from django.shortcuts import HttpResponse, render, redirect
1. HttpResponse('字符串') 用来返回具体的字符串
2. render(request, 'xx.html') 用户返回一个html页面
3. redirect 重定向 跳转
1. 路由是一个有顺序的列表,从上到下去匹配
2. 路由的路径是根据正则表达式来匹配的
基本模板引擎(templates/xx.html)
1. render(request, 'xx.html', {"k": "v"})
2. 经常使用语法:
1. {{ 变量名 }}
2. {{ 变量名.key }}
3. for循环
{% for x in xx %}
{{x}}
{% endfor %}
4. if判断
{% if 条件 %}
...
{% else %}
...
{% endif %}
MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller),具备耦合性低、重用性高、生命周期成本低等优势。
Django框架的设计模式借鉴了MVC框架的思想,也是分红三部分,来下降各个部分之间的耦合性。
Django框架的不一样之处在于它拆分的三部分为:Model(模型)、Template(模板)和View(视图),也就是MTV框架。
Model(模型):负责业务对象与数据库的对象(ORM)
Template(模版):负责如何把页面展现给用户
View(视图):负责业务逻辑,并在适当的时候调用Model和Template
此外,Django还有一个urls分发器,它的做用是将一个个URL的页面请求分发给不一样的view处理,view再调用相应的Model和Template
1)在urls.py文件中添加访问url和将要执行的函数对应关系;
2)在views.py中添加login函数;
3)在templates下添加login.html页面;
4)完善views.py中添加login函数:
备注:报错403,找到如下代码注释。
一、在项目目录下新建一个保存静态文件的文件夹,把bootstrap包放在此路径下;
二、settings.py中加上相应的配置项,告诉Django在新建的路径下去找静态文件;
三、在HTML页面中使用刚才配置的静态文件,使用/static/... 来引用;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"> </head> <body> <h1 style="text-align: center">登陆页面</h1> <div class="container"> <div class="row"> <div class="col-md-4 col-md-offset-4" style="margin-top: 70px"> <form action="/login/" method="post"> <div class="form-group"> <label for="exampleInputEmail1">用户名</label> <input type="text" name="username" class="form-control" id="exampleInputEmail1" placeholder="用户名"> </div> <div class="form-group"> <label for="exampleInputPassword1">密码</label> <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="密码"> </div> <button type="submit" class="btn btn-default">登陆</button> </form> </div> </div> </div> </body> </html>
1. 用pymysql链接MySQL数据库查询数据
1. import pymysql
2. 创建链接
3. 获取光标
4. 执行SQL语句
5. 获取数据
6. 关闭光标
7. 关闭链接
2. 使用pymysql链接数据库缺点:
1. 麻烦
2. 本身写SQL语句!!! 执行效率不高
3. 使用ORM工具链接数据库
- 优势:
1. 不用本身写SQL语句!!! 开发效率高
- 缺点:
1. 执行效率不高
4. 什么是ORM?
对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不一样类型系统的数据之间的转换
[1]
。从效果上说,它实际上是建立了一个可在编程语言里使用的--“虚拟对象数据库”。
1)对象关系映射
类 数据表
属性 字段
对象 数据行
5. ORM的使用
1. 操做数据表
2. 操做数据行
6. Django中如何使用ORM
1. 告诉Django链接哪一个MySQL数据库(settings.py)
2. 告诉Django用pymysql链接MySQL数据库 (默认用的是MySQLDB 这个是在python2使用的模块)
3. 去app/models.py里面建立类
4. 让Django去数据库帮我建立类对应的数据表
1. python manage.py makemigrations --> 记录models.py的任何改动 记录在migrations目录下
2. python manage.py migrate --> 将变动记录翻译成SQL语句,去数据库执行
7. ORM单表的增删改查
1. 查询
models.Publisher.objects.all() --> 查询全部的出版社数据
models.Publisher.objects.get(id=1) --> 查询id=1的那个出版社
2. 增长
models.Publisher.objects.create(name='xx') --> 建立一个名为xx的出版社
3. 删除
models.Publisher.objects.get(id=2).delete() --> 删除id=2的那个出版社
4. 编辑
obj = models.Publisher.objects.get(id=2) --> 找到要编辑的对象
obj.name = "新值" --> 修改
obj.save()
1)告诉Django链接sqlite数据库(settings.py);
2)在migrations下的_init_.py中,不须要添加任何内容(由于默认用的是sqlite3);
3)去app/models.py里面建立类;
4)让Django去数据库帮我建立类对应的数据表;
5)在pycharm中链接sqlite3数据库;
6)若是以前没有链接过,须要先下载一下,点击蓝色字体的download;
7)能够在file下,找到sqlite3文件的路径或者直接点击ok后,把项目目录下的sqlite3直接拖动到右侧打开的数据库中;
1)告诉Django链接哪一个MySQL数据库(settings.py);
2)告诉Django用pymysql链接MySQL数据库 (默认用的是MySQLDB 这个是在python2使用的模块);
3)去app/models.py里面建立类;
4)让Django去数据库帮我建立类对应的数据表;
1)使用pycharm自带的数据库工具:
选择Database>>Data Sourse>>MySQL;
点击Download,下载驱动;
输入主机、数据库名、用户名、密码,测试链接成功后,点击ok;
1)urls.py文件
"""mysite2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url # from django.contrib import admin from app01 import views #用户访问url和将要执行函数的对应关系 urlpatterns = [ # url( r'^admin/', admin.site.urls ), url( r'^index/$', views.index ), url( r'^login/$',views.login), # 出版社列表页 url(r'publisher_list/',views.publisher_list), # 添加出版社 url(r'add_publisher/',views.add_publisher), # 删除出版社 url(r'delete_publisher/',views.delete_publisher), # 编辑出版社 url(r'edit_publisher/',views.edit_publisher), ]
2)views.py文件
from django.shortcuts import render # Create your views here. from django.shortcuts import HttpResponse, render ,redirect from app01 import models #定义一些用户请求处理的函数 def index(request): """ :param request: 全部跟用户请求相关的数据都封装到了一个名为request的对象中 :return: """ # print(request.method) # 获取到用户请求的方法 # print(request.path_info) # 拿到用户请求的路径 # 本身找文件打开而后读取内容 # with open('index.html','rb') as f: # data = f.read() # return HttpResponse(data) #Django帮我打开html文件,而后把文件里面的内容读取出来给用户返回 return render(request,"index.html") # 登陆页面 def login(request): # 根据用户发送请求的方法不一样,作不一样的操做 print(request.method) if request.method == "POST": # 表示用户给我提交用户名和密码数据了 # 从request中取用户 post 过来的数据 print(request.POST) # 是一个大字典 # 用户名密码正确性校验 username = request.POST.get("username", "") pwd = request.POST.get("password", "") if username == "admin" and pwd == "123456": # 登录成功 # return HttpResponse("登录成功") # 跳转到index页面,让用户的浏览器去访问新的页面(index页面) return redirect("/index/") else: # 登陆失败 return HttpResponse("登陆失败") # 给用户返回一个页面 用来作登陆 return render(request, 'login.html') # 出版社列表 def publisher_list(request): # 一、查询出全部的出版社数据 data = models.Publisher.objects.all() print(data) # 二、在页面上显示、将页面数据返回给用户 return render(request,"publisher_list.html",{"data":data}) # 添加出版社 def add_publisher(request): # 当请求方法是POST的时候,表示用户填写完成出版社名字 给我发数据了 if request.method == "POST": # 一、取到用户发送的数据 publisher_name = request.POST.get("publisher_name") # 二、取数据库存储 models.Publisher.objects.create(name = publisher_name) # 三、给用户返回响应, 让用户跳转到出版社列表页面 return redirect("/publisher_list/") return render(request,"add_publisher.html") # 删除出版社 def delete_publisher(request): print(request.GET) # 一、取到用户要删除的那一条数据 delete_id = request.GET.get("id") # 二、去数据库删除掉 models.Publisher.objects.get(id = delete_id).delete() # 三、删除成功以后, 再跳转回出版社列表页面 return redirect("/publisher_list/") # 编辑出版社 def edit_publisher(request): # 当请求方式是POST时,表示用户已经修改完成 给我发修改以后的数据了 if request.method == "POST": # 用户提交过来的数据 edit_id = request.POST.get("id") new_publisher_name = request.POST.get("publisher_name") # 去修改数据库中指定出版社的name字段的值 # 先根据edit_id找到要编辑的出版社 obj = models.Publisher.objects.get(id = edit_id) # 修改出版社的name obj.name = new_publisher_name # 将改动同步到数据库 obj.save() # 编辑成功,跳转到出版社列表页米爱你 return redirect("/publisher_list/") # 一、获取用户要编辑的出版社id edit_id = request.GET.get("id") # 二、根据id去数据库找到这条记录 obj = models.Publisher.objects.get(id = edit_id) # 三、在页面上展现原来出版社名字 return render(request,"edit_publisher.html",{"publisher":obj})
3)查看出版社页面publisher_list.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>出版社列表页面</title> </head> <body> <h1>出版社列表</h1> <p><a href="/add_publisher/">添加新出版社</a></p> <table border="1"> <thead> <tr> <th>序号</th> <th>出版社id</th> <th>出版社名称</th> <th>操做</th> </tr> </thead> <tbody> <!-- 按照Django tempalte的特殊语法 写特殊符号 用来替换数据--> {% for obj in data %} <tr> <td>{{ forloop.counter }}</td> <td>{{ obj.id }}</td> <td>{{ obj.name}}</td> <td> <a href="/edit_publisher/?id={{ obj.id }}">编辑</a> <a href="/delete_publisher/?id={{ obj.id }}">删除</a> </td> </tr> {% endfor %} </tbody> </table> </body> </html>
4)添加出版社页面add_publisher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加出版社</title> </head> <body> <form action="/add_publisher/" method="post"> <input type="text" name="publisher_name" placeholder="新出版社名字"> <button type="submit">添加</button> </form> </body> </html>
5)编辑出版社页面edit_publisher.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>编辑出版社</title> </head> <body> <form action="/edit_publisher/" method="post"> <input type="text" name="id" value="{{ publisher.id }}" style="display: none"> <input type="text" name="publisher_name" value="{{ publisher.name }}"> <button type="submit">提交</button> </form> </body> </html>