Django 框架大致分成3个部分
a-socket服务端
b-根据请求信息提取url路由系统
c-模板渲染 (hrml+css+js)+函数
c 的创建过程
一-首先配置settings.py
1,STATICFLES_DIRS( os.path.join(BASE_DIR, "/static/"))
2,创建templates模板路径
'DIRS': [os.path.join(BASE_DIR, 'templates')]
3,注释Csrf
# 'django.middleware.csrf.CsrfViewMiddleware',
二 -创建HTML模板样式
三-在url.py中写出想要的url
注意不要漏掉 ”/“ 和结尾的 ,
例如:
urlpatterns = [ path('admin/', admin.site.urls), path('teacher/', item.teacher), path('add_teacher/', item.add_teacher), path('del_teacher/', item.del_teacher), path('edit_teacher/', item.edit_teacher), ]
四- 根据URL写出对于的函数
需要数据时要建立pymysql 步骤是固定的 增删改 用 conn.commit 查 用 cursor.fetchall / fetchone
import pymysqlxu from django.shortcuts import render, redirect def teacher(request): conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='day6') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,name from teacher ") result = cursor.fetchall() cursor.close() conn.close() return render(request, 'teacher.html', {'result': result}) def add_teacher(request):l if request.method == 'GET': return render(request, 'add_teacher.html') if request.method == 'POST': name = request.POST.get('name') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='day6') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("insert into teacher(name) values (%s)", [name, ]) conn.commit() cursor.close() conn.close() return redirect('/teacher/') def del_teacher(request): id = request.GET.get('id') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='day6') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("delete from teacher where id=%s", [id, ]) conn.commit() cursor.close() conn.close() return redirect('/teacher/') def edit_teacher(request): if request.method == 'GET': id = request.GET.get('id') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='day6') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,name from teacher where id=%s", [id, ]) result = cursor.fetchone() cursor.close() conn.close() return render(request, 'edit_teacher.html', {'result':result}) if request.method == 'POST': id = request.GET.get('id') name = request.POST.get('name') conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123456', database='day6') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("update teacher set name=%s where id=%s", [name,id, ]) conn.commit() cursor.close() conn.close() return redirect('/teacher/')