日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

表单的增 删 改 查

發(fā)布時(shí)間:2025/7/14 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 表单的增 删 改 查 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

?

django單表操作 增 刪 改 查

?

?

一、實(shí)現(xiàn):增、刪、改、查

1、獲取所有數(shù)據(jù)顯示在頁面上

model.Classes.object.all(),拿到數(shù)據(jù)后,渲染給前端;前端通過for循環(huán)的方式,取出數(shù)據(jù)。

目的:通過classes(班級(jí)表數(shù)據(jù)庫)里面的字段拿到對(duì)應(yīng)的數(shù)據(jù)。

?

2、添加功能

配置url分發(fā)路由增加一個(gè)add_classes.html頁面

寫一個(gè)def?add_classess函數(shù)

在前端寫一個(gè)a標(biāo)簽,前端頁面就可以看到一個(gè)添加鏈接,通過點(diǎn)這個(gè)a標(biāo)簽的鏈接跳轉(zhuǎn)到一個(gè)新的add_classess頁面

add_classess.html 頁面中實(shí)現(xiàn)兩個(gè)功能:

form表單 :返回給add_classess.html頁面

input ?輸入框

input ?提交按鈕

接下來就要接收前端輸入的數(shù)據(jù):

if ?request.mothod='GET'

elif

?request.mothod='POST'

request.POST.get('title') ?拿到傳過來的班級(jí)數(shù)據(jù)

然后通過創(chuàng)建的方式,寫入對(duì)應(yīng)的title字段數(shù)據(jù)庫中

方法:models.Classes.objects.create(titile=title)

再返回給return redirect('/get_classes.html')

?

3、刪除功能

配置url路由分發(fā)

加一個(gè)操作:

<th>操作</th>

一個(gè)a標(biāo)簽:

<a href="/del_classes.html?nid={{ row.id }}">刪除</a>

實(shí)現(xiàn)刪除操作,就是找到數(shù)據(jù)庫中,對(duì)應(yīng)的id字段(賦值給nid=id),刪除掉這個(gè)ID字段這行數(shù)據(jù),就實(shí)現(xiàn)了刪除功能。

?

4、實(shí)現(xiàn)編輯功能

在get_classes.html里添加一個(gè)a標(biāo)簽

配置路由分發(fā)

寫def edit_classes函數(shù)

班級(jí)這個(gè)輸入框前面id不顯示,因?yàn)閕d不能被用戶修改,所以要隱藏。

根據(jù)id拿到這個(gè)對(duì)象(id 走get方法),id存放在請(qǐng)求頭中發(fā)送過去的。

obj對(duì)象里面包含id 和 title ,走post方法,title是放在請(qǐng)求體中發(fā)送過去的

第一次: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')

綜合應(yīng)用示例:

models.py

from django.db import models# Create your models here.class Classes(models.Model):"""班級(jí)表,男"""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

?

項(xiàng)目名: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):# 從數(shù)據(jù)庫中獲取所有的數(shù)據(jù):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) #創(chuàng)建新內(nèi)容(相當(dāng)于前面有個(gè)else,函數(shù)遇見return結(jié)束函數(shù),所以不用寫else,如果沒有return ,必須寫else)return redirect('/publisher/') #返回跳轉(zhuǎn)頁面return render(request,'add_publisher.html')#刪除出版社 def del_publisher(request):#獲取要?jiǎng)h除的對(duì)象iddel_id = request.GET.get('id')del_list = models.Publisher.objects.filter(id=del_id)#篩選刪除的id在Publisher里if del_list:#刪除滿足條件的所有對(duì)象 del_list.delete()return redirect('/publisher/')else:return HttpResponse('刪除失敗')#編輯出版社 def edit_publisher(request):#獲取要編輯的對(duì)象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() # 保存在數(shù)據(jù)庫中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('數(shù)據(jù)不存在') 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>序號(hào)</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

?

轉(zhuǎn)載于:https://www.cnblogs.com/ls13691357174/p/9598219.html

總結(jié)

以上是生活随笔為你收集整理的表单的增 删 改 查的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。