Django框架和前端的的基本结合
1 昨日回顾
a socket
b 路由关系
c 模板字符串替换(模板语言)
主流web框架总结:
django a用别人的 b自己写的 c自己写的
flask a用别人的 b自己写的 c用别人的(jinja2)
tornado a自己写的 b自己写的 c自己写的
另一个维度:
djaogo
其他
创建Django
1 模块安装(三种方法)
1 ---
2 --
3--
2 django-admin startproject mysite
3 manage.py 管理我的django项目
4 (1)启动django--python3
-manage.py runserver 127.0.0.1:8002
-manage.py runserver 8002
-manage.py runserver
(2)pycharm启动:1 跟上面一样
2 点绿色的箭头
不是点右键运行
5 停止 ctrl+c
6 目录介绍
settings--django全局配置文件
urls---路由关系
app:
命令:python3 manage.py startapp app01
目录:
migrations:数据库迁移的文件
admin:后台管理相关
apps:app配置相关
models:模型,数据库相关,写一些类
tests:测试相关
views:视图函数
settings:
DEBUG
INSTALLED_APPS---》放app的名字
MIDDLEWARE--》中间件
TEMPLATES---》指定模板文件放的路径
DATABASES---》指定连接的数据库
静态文件配置:(名字一定不能错)
STATICFILES_DIRS=[
os.path.join(BASE_DIR, 'static'),
]
三件套:
# render 模板渲染
# HttpResponse 返回字符串
# redirect 重定向
orm:对象关系映射
python代码------》sql
前端:
$("#app")------>document.getEmlementById(‘app’)
优点:
1 sql掌握一般,也可开发程序
2 开发效率高
3 易用,学习曲线短
缺点:
1 sql大神,执行效率高,可能orm 执行效率低
2 有的sql写不出来
作业:
1 上课讲的代码敲完
2 写个注册,登录
3 看一下orm(有余力)
项目的基本配置 settings文件
1 """
2 Django settings for mySecond project.
3
4 Generated by 'django-admin startproject' using Django 1.11.
5
6 For more information on this file, see
7 https://docs.djangoproject.com/en/1.11/topics/settings/
8
9 For the full list of settings and their values, see
10 https://docs.djangoproject.com/en/1.11/ref/settings/
11 """
12
13 import os
14
15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16 # 根路径 mySecond
17 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18
19
20 # Quick-start development settings - unsuitable for production
21 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
22
23 # SECURITY WARNING: keep the secret key used in production secret!
24 SECRET_KEY = 'uzz2#7dq+qruh2e6&cklrwj49(oe0&@hwaqqtkmb0z2xmhe03*'
25
26 # SECURITY WARNING: don't run with debug turned on in production!
27 DEBUG = True
28
29 ALLOWED_HOSTS = []
30
31
32 # Application definition
33
34 # 放app的名字
35 INSTALLED_APPS = [
36 'django.contrib.admin',
37 'django.contrib.auth',
38 'django.contrib.contenttypes',
39 'django.contrib.sessions',
40 'django.contrib.messages',
41 'django.contrib.staticfiles',
42 # 新建的功能项目需要添加到INSTALLED_APPS
43 # app01下面的apps里面的App01Config
44 'app01.apps.App01Config',
45 ]
46
47 MIDDLEWARE = [
48 'django.middleware.security.SecurityMiddleware',
49 'django.contrib.sessions.middleware.SessionMiddleware',
50 'django.middleware.common.CommonMiddleware',
51 # 'django.middleware.csrf.CsrfViewMiddleware', 中间件 跨站攻击防护的先注释掉,以后再加上
52 'django.contrib.auth.middleware.AuthenticationMiddleware',
53 'django.contrib.messages.middleware.MessageMiddleware',
54 'django.middleware.clickjacking.XFrameOptionsMiddleware',
55 ]
56
57 ROOT_URLCONF = 'mySecond.urls'
58
59 TEMPLATES = [
60 {
61 'BACKEND': 'django.template.backends.django.DjangoTemplates',
62 # 把模板路径放到里面
63 'DIRS': [os.path.join(BASE_DIR, 'templates')] # 如果创建项目的时候括号里没有内容需要手动加上
64 ,
65 'APP_DIRS': True,
66 'OPTIONS': {
67 'context_processors': [
68 'django.template.context_processors.debug',
69 'django.template.context_processors.request',
70 'django.contrib.auth.context_processors.auth',
71 'django.contrib.messages.context_processors.messages',
72 ],
73 },
74 },
75 ]
76
77 WSGI_APPLICATION = 'mySecond.wsgi.application'
78
79
80 # Database
81 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
82
83 # DATABASES---》指定连接的数据库
84 DATABASES = {
85 'default': {
86 'ENGINE': 'django.db.backends.sqlite3',
87 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
88 }
89 }
90
91
92 # Password validation
93 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
94
95 AUTH_PASSWORD_VALIDATORS = [
96 {
97 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
98 },
99 {
100 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
101 },
102 {
103 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
104 },
105 {
106 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
107 },
108 ]
109
110
111 # Internationalization
112 # https://docs.djangoproject.com/en/1.11/topics/i18n/
113
114 LANGUAGE_CODE = 'en-us'
115
116 TIME_ZONE = 'UTC'
117
118 USE_I18N = True
119
120 USE_L10N = True
121
122 USE_TZ = True
123
124
125 # Static files (CSS, JavaScript, Images)
126 # https://docs.djangoproject.com/en/1.11/howto/static-files/
127
128 # 静态文件配置:(名字一定不能错)
129 # STATICFILES_DIRS=[
130 # os.path.join(BASE_DIR, 'static'),
131 # ]
132 STATIC_URL = '/static/' # 这步相当于做了个接口,通过接口来访问STATICFILES_DIRS
133 # 如果不写static_url这个接口,外面可以直接调用里面的文件
134 STATICFILES_DIRS=[
135 os.path.join(BASE_DIR, 'static'),
136 ]
管理django项目的manage文件
1 #!/usr/bin/env python
2 import os
3 import sys
4
5 if __name__ == "__main__":
6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mySecond.settings")
7 try:
8 from django.core.management import execute_from_command_line
9 except ImportError:
10 # The above import may fail for some other reason. Ensure that the
11 # issue is really that Django is missing to avoid masking other
12 # exceptions on Python 2.
13 try:
14 import django
15 except ImportError:
16 raise ImportError(
17 "Couldn't import Django. Are you sure it's installed and "
18 "available on your PYTHONPATH environment variable? Did you "
19 "forget to activate a virtual environment?"
20 )
21 raise
22 execute_from_command_line(sys.argv)
urls 存放请求地址和函数关系的路由
1 """mySecond URL Configuration
2
3 The `urlpatterns` list routes URLs to views. For more information please see:
4 https://docs.djangoproject.com/en/1.11/topics/http/urls/
5 Examples:
6 Function views
7 1. Add an import: from my_app import views
8 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
9 Class-based views
10 1. Add an import: from other_app.views import Home
11 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
12 Including another URLconf
13 1. Import the include() function: from django.conf.urls import url, include
14 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
15 """
16 from django.conf.urls import url
17 from django.contrib import admin
18 from app01 import views
19 urlpatterns = [
20 url(r'^admin/', admin.site.urls),
21 url(r'^index/', views.index),
22 url(r'^login/', views.login),
23 url(r'^login_submit/', views.login_submit),
24 ]
views 视图函数的存放点
1 from django.shortcuts import render,HttpResponse,redirect
2 # 三件套 render 模板渲染
3 # HttpResponse 返回字符串
4 # redirect 重定向
5 import pymysql
6
7
8 # redirect 重定向
9 # Create your views here.
10
11
12 def index(request):
13 # with open('templates/index','r') as f:
14 # data=f.read()
15 print(request.method)
16
17 # return HttpResponse('<h1>Hellw</h1>')
18 return render(request, 'index.html')
19
20
21 def login111(request):
22 # GET 一定要大写
23 if request.method == 'GET':
24 return render(request, 'login.html')
25 elif request.method == 'POST':
26 name = request.POST['name']
27 # 推荐用这种
28 # request.POST 请求体的内容都在里面,字典形式
29 # <QueryDict: {'name': ['123'], 'password': ['444']}>
30 password = request.POST.get('password', None)
31 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306)
32
33 cursor = conn.cursor(pymysql.cursors.DictCursor)
34 cursor.execute('select * from user where name=%s and password=%s', [name, password])
35 user = cursor.fetchone()
36 if user:
37 return HttpResponse('登录成功')
38 # if name == 'lqz' and password == '123':
39 # # return HttpResponse('登录成功')
40 # return redirect('www.baidu.com')
41 # # return redirect('http://127.0.0.1:8000/index/')
42 else:
43 error = '用户名或密码错误'
44 return render(request, 'login.html', {'error': error})
45
46
47 def login(request):
48 error = ''
49 if request.method == 'POST':
50 name = request.POST['name']
51 password = request.POST.get('password', None)
52 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306)
53 cursor = conn.cursor(pymysql.cursors.DictCursor)
54 cursor.execute('select * from user where name=%s and password=%s', [name, password])
55 user = cursor.fetchone()
56 if user:
57 return HttpResponse('登录成功')
58 else:
59 error = '用户名或密码错误'
60 return render(request, 'login.html', {'error': error})
61
62
63 def login_submit(request):
64 # print(request.get_full_path())
65 # print(request.method)
66 print(request.POST)
67 name = request.POST.get('name',None)
68 # 推荐用这种
69 # request.POST 请求体的内容都在里面,字典形式
70 # <QueryDict: {'name': ['123'], 'password': ['444']}>
71 password = request.POST.get('password', None)
72 if name == 'lqz' and password == '123':
73 # return HttpResponse('登录成功')
74 return redirect('/index/')
75
76 return redirect('/login/')
注意:html结尾的这些文件通常都放在templates下,称作模板
index.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 <link rel="stylesheet" href="/static/css/mycss.css">
7 </head>
8 <body>
9 <h1>Hello</h1>
10 </body>
11 </html>
login.html
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>登录</title>
6 <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.min.css">
7 </head>
8 <body>
9 <div class="container">
10
11 <div class="row">
12
13 <div class="col-md-6 col-md-offset-3">
14
15 <form action="" method="post">
16
17 <p>用户名:<input type="text" name="name" class="form-control" ></p>
18 <p>密码:<input type="password" name="password" class="form-control"></p>
19 <p><input type="submit" value="登录" class="form-control"></p>
20 <p class="text-danger text-center">{{ error }}</p>
21
22
23 </form>
24 </div>
25 </div>
26
27 </div>
28
29
30
31 </body>
32 </html>
static文件:下面存放着css,js,img,bootstrap等。。
最后,附上自己的作业:
1 from django.shortcuts import render,HttpResponse,redirect
2
3 # Create your views here.
4 # 视图层函数里面就是一个个需要通过路由来调用并访问的函数
5 # 调用函数的目的是为了去访问模板层。
6 import pymysql
7
8
9 def index(request):
10 with open('templates/index','r') as f:
11 print(f.read())
12 return render(request,'index.html')
13 # return HttpResponse('<h1>hellowword</h1>')
14
15
16
17
18 def register(request):
19 if request.method == 'GET':
20 return render(request,'register.html')
21 elif request.method == 'POST':
22 name = request.POST.get('name',None)
23 password = request.POST.get('password',None)
24 re_password = request.POST.get('re_password',None)
25 if password != re_password:
26 return HttpResponse('password is not similar')
27 else:
28 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306)
29
30 cursor = conn.cursor(pymysql.cursors.DictCursor)
31 cursor.execute('select * from user where name=%s and password = %s', [name, password])
32 user = cursor.fetchone()
33 if user:
34 return HttpResponse('having the similar user please change the user or password')
35 else:
36 # 数据库建表的时候要递增
37 cursor.execute('insert into user(name,password) values(%s,%s) ', [name, password])
38 print(request.POST.get('name',None))
39 # 必须要提交,否则不会写到数据库里
40 conn.commit()
41 # 必须要有返回值
42 return HttpResponse('sn')
43
44 def login(request):
45 if request.method == 'GET':
46 return render(request,'login.html')
47 elif request.method == 'POST':
48 name = request.POST.get('name',None)
49 password = request.POST.get('password',None)
50 conn = pymysql.connect(host='127.0.0.1', user='root', password="123", database='test', port=3306)
51
52 cursor = conn.cursor(pymysql.cursors.DictCursor)
53 cursor.execute('select * from user where name=%s and password=%s', [name, password])
54 user = cursor.fetchone()
55 if user:
56 return HttpResponse('login success')
57 else:
58 error = "logging fail,relog again"
59 return render(request,'login.html',{'error':error})
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>register</title>
6 <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
7 </head>
8 <body>
9 <div class = 'row'>
10 <div class = 'col-md-6 col-md-offset-3'>
11 <form action="" method = 'post'>
12 <p>user:<input type="text" name="name" class="form-control" ></p>
13 <p>pwd:<input type="password" name="password" class="form-control"></p>
14 <p>re_pwd:<input type="password" name="re_password" class="form-control"></p>
15 <p><input type="submit" value="register" class="form-control"></p>
16 <p class="text-danger text-center">{{ error }}</p>
17 </form>
18 </div>
19 </div>
20
21 </body>
22 </html>
越是困难的事越要立即去做,这样收益才会最大!!!