目录
Django 是根据比利时的爵士音乐家Django Reinhard命名,django的工作基本原理:
用户发送请求(http://www.163.com)----------->WSGI规范------------>在django urls.py中找对应的地址-------->在django views中找对应的逻辑方法 ----------->处理models的操作--------->数据库与模板耦合--------->在templates找到相应的视图模板 ---------->显示给用户处理结果视图
一、认识web框架
1.web框架介绍
具体介绍Django之前,必须先介绍WEB框架等概念。
web框架: 别人已经设定好的一个web网站模板,你学习它的规则,然后“填空”或“修改”成你自己需要的样子。
一般web框架的架构是这样的:
其它基于python的web框架,如tornado、flask、webpy都是在这个范围内进行增删裁剪的。例如tornado用的是自己的异步非阻塞“wsgi”,flask则只提供了最精简和基本的框架。Django则是直接使用了WSGI,并实现了大部分功能。
2. MVC/MTV介绍
MVC百度百科:全名Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。
通俗解释:一种文件的组织和管理形式!不要被缩写吓到了,这其实就是把不同类型的文件放到不同的目录下的一种方法,然后取了个高大上的名字。当然,它带来的好处有很多,比如前后端分离,松耦合等等,就不详细说明了。
模型(model):定义数据库相关的内容,一般放在models.py文件中。
视图(view):定义HTML等静态网页文件相关,也就是那些html、css、js等前端的东西。
控制器(controller):定义业务逻辑相关,就是你的主要代码。
MVT: 有些WEB框架觉得MVC的字面意思很别扭,就给它改了一下。view不再是HTML相关,而是主业务逻辑了,相当于控制器。html被放在Templates中,称作模板,于是MVC就变成了MTV。且将CSS、JS等静态文件存放与static目录中
models模型(数据模型)
views视图 (view+controller控制器)
templates模板(页面模板,一般前端开发页面,后端根据前端开发的页面修改为模板,正序分析,倒序开发)
二、认识Django模块
1.django框架逻辑图
2.django项目目录结构图
3、安装django模块
pip install django
4.安装MySQLdb模块
4.1.python2.x中安装MySQLdb
在 python2 中,使用 pip install mysql-python
进行安装连接MySQL的库,使用时 import MySQLdb
进行使用
4.2.python3.x中安装MySQLdb
在 python3 中,改变了连接库,改为了 pymysql
库,使用pip install pymysql
进行安装,直接导入即可使用
但是在 Django 中, 连接数据库时使用的是 MySQLdb 库,这在与 python3 的合作中就会报以下错误了
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'
解决方法:在 __init__.py 文件中添加以下代码即可。
import pymysql
pymysql.install_as_MySQLdb()
4.3需要手动在mysql内创建数据库才能通过django连通:
创建数据库:create database databasename default charset=utf8;
三、Django实例
需要在shell中编写python代码时,需要使用manage.py文件来启动shell:
python3 manage.py shell
1、创建django的项目和模块:
执行命令:django-admin startproject 项目名称和django-admin startapp 模块名称
y@2018:#django-admin startproject mypro#生成项目目录、项目目录下会自动生成主程序目录
y@2018:~/django0923$ ls /mypro
manage.py mypro
y@2018:#cd mypro
y@2018:#django-admin startapp testdjango#在项目目录内生成应用模块目录
#目录结构
y@2018:~/django0923/mypro$ ls
manage.py mypro testdjango
2、配置项目
在settings.py中配置,以新增应用、连接数据库、配置模板等功能
2.1 新增模块配置
INSTALLED_APPS={
应用名称
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'testdjango'
]
2.2 连接数据库配置
DATABASES={
}
将 ‘ENGINE'改成mysql
'HOST'大写,数据库服务器的名称
'PORT'大写,数据库服务器的端口 3306
'USER'大写,数据库服务器的登陆名 root
'PASSWORD'大写,数据库服务器的密码
'NAME'大写,数据库服务器的数据库名
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':'127.0.0.1',
'PORT':3306,
'USER':'root',
'PASSWORD':'root',
'NAME':'testdjango'
}
}
2.3 模板配置:
在TEMPLATES={ }
DIRS里加模板的路径 os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
2.4静态文件路径配置
STATIC_URL = '/static/'#此变量名默认存在,无需新增
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]
3、路由系统
修改~mypro/mypro下的urls.py: url(r'^view处理函数$',views.index)
注意:在view.py中每新增一个方法,需要在url.py文件新增一个元素
from django.contrib import admin
from django.urls import path
from testdjango import views#需要手动导入
from django.conf.urls import url#需要手动导入
urlpatterns = [
path('admin/', admin.site.urls),
url(r'test_django/',views.index)
]
4、定义数据模型(即数据库中表格字段)
4.1修改~/mypro/testdjango中的models.py,定义一个类,models的类与数据库的表名相对应,
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class test_django(models.Model):#别忘了需要继承models.Model
name=models.CharField(max_length=20)# CharField相当于varchar(20)
4.2同步数据库:
根据models.py产生数据库的表
python3 manage.py makemigrations
python3 manage.py migrate
y@2018:~/django0923/mypro$ python3 manage.py makemigrations
#返回值
Migrations for 'testdjango':
testdjango/migrations/0001_initial.py
- Create model test_django
y@2018:~/django0923/mypro$ python3 manage.py migrate
#返回值
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, testdjango
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
Applying testdjango.0001_initial... OK
4.3在数据库加入数据(------------------------------存疑,待解决)
利用django的后台
新建用户
python manage.py createsuperuser
在我们自己的表中填数据,先注册
zelin@2018:~/django0923/mypro$ python3 manage.py createsuperuser
Username (leave blank to use 'zelin'): testdjango
Email address: 12@qq.com
Password: #a12345.12345
Password (again):
Superuser created successfully.
在/mypro/testdjango/admin.py从~/mypro/testdjango/models.py中导入类
在应用下面的admin.py,导入一下models里面的类
admin.site.register(UserInfo)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import test_django#手动导入
# Register your models here.
admin.site.register(test_django)
5、业务逻辑设计
修改在应用的目录下的views.py:
return
HttpResponse(”直接跟字符串")
render(request,'网页',字典类变量)
(1)返回HttpResponse
(2)返回不带参的网页
(3)返回带参的网页: user=UserInfo.objects.all()
5.1新增响应
添加一个index方法:
def index(request):request是参数
return HttpResponse("ok");
返回给浏览器的信息
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse#需要手动导入
# Create your views here.
def index(request):
return HttpResponse('ok')
5.2新增模板
注释掉新增的响应,新增以下代码
def index(request):
return render(request,'index.html')
先把对象全部显示,引入UserInfo
UserInfo.objects.all()相当于select * from userinfo
定义一个字典类的变量
context={'user':users}
传入render参数中,
return render(request,'index.html',context)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import test_django#手动导入
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse('ok')
users=test_django.objects.all()
context={'user':users}
return render(request,'index.html',context)
6、启动服务器
执行这个django项目,表示网站服务器已开启,可以登录网页:http://127.0.0.1:8000/test_django/
在manage.py所在的目录下
python3 manage.py runserver
y@2018:~/django0923/mypro$ python3 manage.py runserver#服务器挂起
Performing system checks...
System check identified no issues (0 silenced).
September 29, 2018 - 09:21:49
Django version 2.1.1, using settings 'mypro.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
5.10 新建tempplates目录,tempplates目下存放.html文件,即模板,模板内输出{{user}}
y@2018:~/django0923/mypro$ mkdir tempplates
y@2018:~/django0923/mypro$ ls
manage.py mypro tempplates testdjango
最后修改模板,即html文件
在模板中直接输出{{}}
{{传入参数字典的键名}}
如果键是一个列表
for循环遍历
{% for u in user(键名) %}
{%endfor%}endfor是必须有一个停止的信息
中间输出对象的属性
{{u.username}}
{{u.password}}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf8>
<title>我的网页</title>
</head>
<body>
<h1>这是我的网页</h1>
<h3>{{user}}</h3>
{% for u in user %}
<h3>{{u.username}}</h3>
<h3>{{u.password}}</h3>
{% endfor %}
</body>
</html>
5.13、登陆django自带后台
http://locahost:8000/admin
5.14、登录django页面
http://localhost:8000/testdjango