django单表操作 增 删 改 查
一、实现:增、删、改、查
1、获取所有数据显示在页面上
model.Classes.object.all(),拿到数据后,渲染给前端;前端通过for循环的方式,取出数据。
目的:通过classes(班级表数据库)里面的字段拿到对应的数据。
2、添加功能
配置url分发路由增加一个add_classes.html页面
写一个def add_classess函数
在前端写一个a标签,前端页面就可以看到一个添加链接,通过点这个a标签的链接跳转到一个新的add_classess页面
add_classess.html 页面中实现两个功能:
form表单 :返回给add_classess.html页面
input 输入框
input 提交按钮
接下来就要接收前端输入的数据:
if request.mothod='GET'
elif
request.mothod='POST'
request.POST.get('title') 拿到传过来的班级数据
然后通过创建的方式,写入对应的title字段数据库中
方法:models.Classes.objects.create(titile=title)
再返回给return redirect('/get_classes.html')
3、删除功能
配置url路由分发
加一个操作:
<th>操作</th>
一个a标签:
<a href="/del_classes.html?nid={{ row.id }}">删除</a>
实现删除操作,就是找到数据库中,对应的id字段(赋值给nid=id),删除掉这个ID字段这行数据,就实现了删除功能。
4、实现编辑功能
在get_classes.html里添加一个a标签
配置路由分发
写def edit_classes函数
班级这个输入框前面id不显示,因为id不能被用户修改,所以要隐藏。
根据id拿到这个对象(id 走get方法),id存放在请求头中发送过去的。
obj对象里面包含id 和 title ,走post方法,title是放在请求体中发送过去的
第一次:get拿到id
if request.method == 'GET': nid = request.GET.get('nid') obj = models.Classes.objects.filter(id=nid).first() return render(request, 'edit_classes.html', {'obj': obj})
第二次:post拿到id和title
elif request.method == 'POST': nid = request.GET.get('nid') title = request.POST.get('title') models.Classes.objects.filter(id=nid).update(titile=title) return redirect('/get_classes.html')
综合应用示例:
models.py
from django.db import models # Create your models here. class Classes(models.Model): """ 班级表,男 """ titile = models.CharField(max_length=32) m = models.ManyToManyField("Teachers") class Teachers(models.Model): """ 老师表,女 """ name = models.CharField (max_length=32) """ cid_id tid_id 1 1 1 2 6 1 1000 1000 """ # class C2T(models.Model): # cid = models.ForeignKey(Classes) # tid = models.ForeignKey(Teachers) class Student(models.Model): username = models.CharField(max_length=32) age = models.IntegerField() gender = models.BooleanField() cs = models.ForeignKey(Classes)
urls.py
"""django_one URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/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.views import classes urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^get_classes.html$', classes.get_classes), url(r'^add_classes.html$', classes.add_classes), url(r'^del_classes.html$', classes.del_classes), url(r'^edit_classes.html$', classes.edit_classes), ]
classes.py
from django.shortcuts import render from django.shortcuts import redirect from app01 import models def get_classes(request): cls_list = models.Classes.objects.all() return render(request, 'get_classes.html', {'cls_list': cls_list}) def add_classes(request): if request.method == "GET": return render(request, 'add_classes.html') elif request.method == 'POST': title = request.POST.get('titile') models.Classes.objects.create(titile=title) return redirect('/get_classes.html') def del_classes(request): nid = request.GET.get('nid') models.Classes.objects.filter(id=nid).delete() return redirect('/get_classes.html') def edit_classes(request): if request.method == 'GET': nid = request.GET.get('nid') obj = models.Classes.objects.filter(id=nid).first() return render(request, 'edit_classes.html', {'obj': obj}) elif request.method == 'POST': nid = request.GET.get('nid') title = request.POST.get('title') models.Classes.objects.filter(id=nid).update(titile=title) return redirect('/get_classes.html')
get_classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <a href="/add_classes.html">添加</a> </div> <div> <table border="1"> <thead> <tr> <th>ID</th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> {% for row in cls_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.titile }}</td> <td> <a href="/del_classes.html?nid={{ row.id }}">删除</a> | <a href="/edit_classes.html?nid={{ row.id }}">编辑</a> </td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
add_classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="add_classes.html" method="POST"> {% csrf_token %} <input type="text" name="titile" /> <input type="submit" value="提交" /> </form> </body> </html>
edit_classes.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <form action="/edit_classes.html?nid={{ obj.id }}" method="POST"> {% csrf_token %} <input type="text" name="title" value="{{ obj.titile }}" /> <input type="submit" value="提交"/> </form> </body> </html>
项目名:LibraryManager
APP名: APP01:
LibraryManager文件中:
__init__:
import pymysql pymysql.install_as_MySQLdb()
setting配置:
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', ]
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', ], }, }, ]
WSGI_APPLICATION = 'LibraryManager.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'library', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': 3306, } }
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ]
urls.py:
"""LibraryManager 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 urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^publisher/',views.publisher_list), url(r'^add_publisher/',views.add_publisher), url(r'^del_publisher/',views.del_publisher), url(r'^edit_publisher/',views.edit_publisher), ]
APP01文件中:
admin.py:
from django.contrib import admin # Register your models here.
apps.py:
from django.apps import AppConfig class App01Config(AppConfig): name = 'app01'
models.py:
from django.db import models class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=32,unique=True) def __str__(self): return self.name
views.py:
from django.shortcuts import render,HttpResponse,redirect from app01 import models def publisher_list(request): # 从数据库中获取所有的数据: publisher_obj_list = models.Publisher.objects.all().order_by('-id') return render(request,'publisher_list.html',{'publishers':publisher_obj_list}) # 添加出版社 # def add_publisher(request): # add_name,err_msg = '','' # if request.method=='POST': # add_name = request.POST.get('new_name') # pub_list = models.Publisher.objects.filter(name=add_name) # if add_name and not pub_list: # models.Publisher.objects.create(name=add_name) # return redirect('/publisher/') # if not add_name: # err_msg='不能为空' # if pub_list: # err_msg='出版社已存在' # return render(request,'add_publisher.html',{'err_name':add_name,'err_msg':err_msg}) # 添加出版社 def add_publisher(request): if request.method == 'POST': #选择提交方式 add_name = request.POST.get('new_name') #获取新添加的名字赋值给add_name if not add_name: #如果名字不存在为空 return render(request, 'add_publisher.html', {"err_name": add_name, 'err_msg': '不能为空'}) pub_list = models.Publisher.objects.filter(name=add_name) #过滤添加的name在不在Publisher表里 if pub_list: # 如果存在表里 return render(request, 'add_publisher.html',{"err_name":add_name,'err_msg':'出版社已存在'}) models.Publisher.objects.create(name=add_name) #创建新内容(相当于前面有个else,函数遇见return结束函数,所以不用写else,如果没有return ,必须写else) return redirect('/publisher/') #返回跳转页面 return render(request,'add_publisher.html') #删除出版社 def del_publisher(request): #获取要删除的对象id del_id = request.GET.get('id') del_list = models.Publisher.objects.filter(id=del_id)#筛选删除的id在Publisher里 if del_list: #删除满足条件的所有对象 del_list.delete() return redirect('/publisher/') else: return HttpResponse('删除失败') #编辑出版社 def edit_publisher(request): #获取要编辑的对象id edit_id = request.GET.get('id') edit_list = models.Publisher.objects.filter(id=edit_id)#筛选要编辑的id在Publisher里赋值给左边 err_msg = '' if request.method == 'POST': edit_name = request.POST.get('new_name')#获得输入新的出版社的名字 print(edit_name,type(edit_name)) check_list = models.Publisher.objects.filter(name=edit_name)#判断在不在原来的表里 if edit_name and edit_list and not check_list: edit_obj = edit_list[0] edit_obj.name = edit_name #新的出版社赋值给要编辑的出版社 edit_obj.save() # 保存在数据库中 return redirect('/publisher/') if check_list: err_msg = '出版社已存在' if not edit_name: err_msg = '出版社不能为空' if edit_list: edit_obj = edit_list[0] #从表里获取的 return render(request,'edit_publisher.html',{'old_obj':edit_obj,'err_msg':err_msg}) else: return HttpResponse('数据不存在')
templates文件夹中:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加出版社</title> </head> <body> <h1>添加出版社</h1> <form action="" method="post"> <p>名称:<input type="text" name="new_name" value="{{ err_name }}"></p><span>{{ err_msg }}</span> <button>提交</button> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>编辑出版社</title> </head> <body> <h1>编辑出版社</h1> <form action="" method="post"> <p>名称:<input type="text" name="new_name" value="{{ old_obj.name }}"></p><span>{{ err_msg }}</span> <button>提交</button> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/add_publisher/">添加出版社</a> <table border="1"> <thead> <tr> <th>序号</th> <th>ID</th> <th>出版社名称</th> <th>操作</th> </tr> </thead> <tbody> {% for publisher in publishers %} <tr> <td>{{ forloop.counter }}</td> <td>{{ publisher.id }}</td> <td>{{ publisher.name }}</td> <td> <a href="/del_publisher/?id={{ publisher.id }}"><button>删除</button></a> <a href="/edit_publisher/?id={{ publisher.id }}"><button>编辑</button></a> </td> </tr> {% endfor %} </tbody> </table> </body> </html>
manage.py:
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "LibraryManager.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)