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_id1    11    26    11000  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)

View Code

urls.py

"""django_one URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views1. Add an import:  from my_app import views2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views1. Add an import:  from other_app.views import Home2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.conf.urls import url, include2. 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 classesurlpatterns = [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),]

View Code

classes.py

from django.shortcuts import render
from django.shortcuts import redirect
from app01 import modelsdef 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')

View Code

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>

View Code

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>

View Code

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>

View Code

项目名:LibraryManager

APP名: APP01:

LibraryManager文件中:

__init__:

import pymysql
pymysql.install_as_MySQLdb()

View Code

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',],},},
]

DIRS填写路径

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,}
}

DATABASES填写信息

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')
]

STATIC_URL下面填写

urls.py:

"""LibraryManager URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views1. Add an import:  from my_app import views2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views1. Add an import:  from other_app.views import Home2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf1. Import the include() function: from django.conf.urls import url, include2. 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),
]

View Code

APP01文件中:

admin.py:

from django.contrib import admin# Register your models here.

View Code

apps.py:

from django.apps import AppConfigclass App01Config(AppConfig):name = 'app01'

View Code

models.py:

from django.db import modelsclass Publisher(models.Model):id = models.AutoField(primary_key=True)name = models.CharField(max_length=32,unique=True)def __str__(self):return self.name

View Code

views.py:

from django.shortcuts import render,HttpResponse,redirect
from app01 import modelsdef 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_nameif 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):#获取要删除的对象iddel_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):#获取要编辑的对象idedit_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('数据不存在')

View Code

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>

add_publisher.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>

edit_publisher.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>

publisger_list.html

manage.py:

#!/usr/bin/env python
import os
import sysif __name__ == "__main__":os.environ.setdefault("DJANGO_SETTINGS_MODULE", "LibraryManager.settings")try:from django.core.management import execute_from_command_lineexcept 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 djangoexcept 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?")raiseexecute_from_command_line(sys.argv)

View Code

转载于:https://www.cnblogs.com/ls13691357174/p/9598219.html

表单的增 删 改 查相关推荐

  1. properties(map)增.删.改.查.遍历

    import java.util.Map; import java.util.Properties; import java.util.Set;/*** properties(map)增.删.改.查. ...

  2. python学生姓名添加删除_python-函数-实现学生管理系统,完成对学员的增,删,改,查和退出学生管理系统。...

    实现学生管理系统,完成对学员的增,删,改,查和退出学生管理系统. 要求1:使用一个list用于保存学生的姓名. 要求2:输入0显示所有学员信息,1代表增加,2代表删除,3代表修改,4代表查询,exit ...

  3. PySpark︱DataFrame操作指南:增/删/改/查/合并/统计与数据处理

    笔者最近需要使用pyspark进行数据整理,于是乎给自己整理一份使用指南.pyspark.dataframe跟pandas的差别还是挺大的. 文章目录 1.-------- 查 -------- -- ...

  4. Go 学习笔记(50)— Go 标准库之 net/url(查询转义、查询参数增/删/改/查、解析URL)

    1. URL 概述 import "net/url" url 包解析 URL 并实现了查询的转码.URL 提供了一种定位因特网上任意资源的手段,但这些资源是可以通过各种不同的方案( ...

  5. oracle 主键 字典表,oracle 增 删 改 查 新建表 主键 序列 数据字典

    ------------数据字典------------ select * from dba_tab_cols a where a.table_name='DEMO' create table dem ...

  6. Linux技术--mysql数据库增-删-改-查

    # mysql 数据库 ## 数据库的操作 ### 五个单位 * 数据库服务器   Linux或者 windows  * 数据库  * 数据表 * 数据字段 * 数据行 ### 连接数据库 ``` 1 ...

  7. 数据结构 严薇敏 顺序表的实现(增 删 改)及其使用方法详解

    时间复杂度 数据结构 时间复杂度和空间复杂度 目录 1.线性表 2.顺序表 2.1概念及结构 2.2 接口实现 SeqList.h SeqList.c 2.2.1初始化链表以及销毁链表的实现 初始化顺 ...

  8. list 增 删 改 查 及 公共方法

    1 # 热身题目:增加名字,并且按q(不论大小写)退出程序 2 li = ['taibai','alex','wusir','egon','女神'] 3 while 1: 4 username = i ...

  9. pyRedis - 操作指南:增/删/改/查、管道与发布订阅功能

    文章目录 1 redis docker 部署与安装 2 py - redis的使用 2.1 redis的连接 2.2 常规属性查看 2.2.2 关于删除 2.3 STRING 字符串的操作 2.4 H ...

最新文章

  1. 【c语言】输入一个4位数,求四位数中各位数相加之和
  2. python处理完数据导入数据库_python操作数据库之批量导入
  3. (科普帖)电梯突然断电下坠时、一定要这么做
  4. 【题意+解析】1041 Be Unique (20 分)_18行代码AC
  5. Mysql剖析单条查询三种方法
  6. 真希望永远用不到这些代码
  7. 二、uniapp项目(分段器的使用、scroll-view、视频下载、转发)
  8. 力扣——最长公共前缀
  9. ios android 系统字体,ios、android 系统字体说明
  10. MAC下maven本地仓库配置
  11. linux虚拟磁带机管理,RHEL6 虚拟磁带机使用指南
  12. Redis过期策略以及内存淘汰机制
  13. linux实验报告ALU,《linux内核分析》第一次课 实验作业
  14. Android Studio 4.2Previw版本编译错误提示Disable offline mode and rerun the build
  15. java中怎么输入中文_MultiMC下载-MultiMC中文实用版 v1.0
  16. 北大韦神等十人获奖,均分1000万元,达摩院2021青橙奖出炉
  17. afterlogic webmail lite php,windows内网邮件服务器搭建(hMailserver+ AfterLogic WebMail Lite)
  18. C语言游戏之贪吃蛇--链表实现
  19. 写给自己以及各位程序员,无论你在什么位置,我想你都应该看一下
  20. Mandatory condition is missing

热门文章

  1. C#的变迁史 - C# 2.0篇
  2. java8 - 新的时间日期API示例
  3. 影响SDN和NFV部署速度的两个因素
  4. 河南省住建厅调研新郑智慧城市建设 市民享受服务便利
  5. Logback Pattern 日志格式配置
  6. 什么是xmlschema
  7. python fabric使用
  8. word break
  9. 网页制作中的背景处理
  10. ubuntu12.04没有输入法。。