0


使用Django框架实现对数据库的增删改查

使用Django框架实现对数据库的增删改查


文章目录


准备

[小白必看]
1.创建Django程序,安装Django服务.点击跳转
2.安装mysqlclient服务,配置数据库.点击跳转
3.启动mysql服务,创建一个要用的数据库.
4.创建子应用,创建并执行迁移文件.走你


一、配置settings.py文件

"""
Django settings for 增删改查 project.

Generated by 'django-admin startproject' using Django 3.1.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY ='a#cmjl*d09^fvgya7_*yji$nbr=$wh!fue@en*-ey)+x7p&$$r'# SECURITY WARNING: don't run with debug turned on in production!
DEBUG =True

ALLOWED_HOSTS =[]# Application definition

INSTALLED_APPS =['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','stu',]

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

ROOT_URLCONF ='增删改查.urls'

TEMPLATES =[{'BACKEND':'django.template.backends.django.DjangoTemplates','DIRS':[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 ='增删改查.wsgi.application'# Database# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES ={'default':{'ENGINE':'django.db.backends.mysql','NAME':'student',# 数据库名称'USER':'root',# 用户名'PASSWORD':'root',# 密码'HOST':'localhost',# 本地ip'PORT':3306,# 端口号}}# Password validation# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS =[{'NAME':'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',},{'NAME':'django.contrib.auth.password_validation.MinimumLengthValidator',},{'NAME':'django.contrib.auth.password_validation.CommonPasswordValidator',},{'NAME':'django.contrib.auth.password_validation.NumericPasswordValidator',},]# Internationalization# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE ='en-us'

TIME_ZONE ='UTC'

USE_I18N =True

USE_L10N =True

USE_TZ =True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL ='/static/'

二、配置urls.py文件

1.初始化应用下的urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns =[
    path('admin/', admin.site.urls),
    path('stu/', include('stu.urls')),]

2.子应用下的urls.py

from django.urls import path
from stu import views

urlpatterns =[
    path('seleAll/', views.seleAll),
    path('delStu/', views.delStu),
    path('updStu/', views.updStu),
    path('seleOne/', views.seleOne),
    path('seleStu/', views.seleStu),]

三.创建模型类models.py

1.使用逆向创建数据库模型

在terminal控制台中输入:

python manage.py inspectdb>stu/models.py
关键字:inspectdb>
stu是我的子应用名称
models.py是存放模型类的文件名称

2.手动编写模型类

from django.db import models

classStu(models.Model):id= models.AutoField(primary_key=True)
    sname = models.CharField(max_length=10)
    spwd = models.CharField(max_length=10)classMeta:
        managed =False
        db_table ='stu'def__str__(self):returnf'id:{self.id},sname:{self.sname},spwd={self.spwd}'

四.编写views.py视图层文件

from django.http import HttpResponse
from django.shortcuts import render, redirect

from stu.models import Stu

# 查询所有defseleAll(request):# 查询所有,相当于select * from stu
    Stus = Stu.objects.all()# 将获得的数据以对象的形式返回到页面中return render(request,'seleAll.html',{'stus': Stus})# 根据id删除单个数据defdelStu(request):
    sid = request.GET.get('sid')if sid isnotNone:# 删除
        Stu.objects.get(id=sid).delete()# 重定向return redirect('/stu/seleAll/')else:return HttpResponse('<h1>删除失败!!</h1>')# 根据id修改defupdStu(request):if request.method =='GET':# get请求就是在页面点击进来的
        sid = request.GET.get('sid')
        stu = Stu.objects.get(id=sid)return render(request,'updateStu.html',{'stu': stu})else:# post请求就是表单提交修改后的数据
        sid = request.POST.get('sid')
        sname = request.POST.get('sname')
        spwd = request.POST.get('spwd')# filter是过滤
        st = Stu.objects.filter(id=sid).update(sname=sname, spwd=spwd)if st==1:return redirect('/stu/seleAll')else:return HttpResponse('<h1>修改失败!!</h1>')# 详情页查询defseleOne(request):# 将查询和获取数据写在一起的方式
    stu = Stu.objects.get(id=request.GET.get('sid'))# stu不是空就进入if stu isnotNone:return render(request,'seleOne.html',{'stu': stu})else:return HttpResponse("<h1>没有查询到该数据!</h1>")# 三重查询defseleStu(request):# 获取要查询的元素
    stu = request.GET.get('Tstu')try:# 如果以id查询出结果的话,就进入else,如果出错了就进入except
        stuId = Stu.objects.get(id=stu)print(stuId)except:try:# 如果以sname查询出结果的话,就进入else,如果出错了就进入except
            stuSname = Stu.objects.get(sname=stu)print(stuSname)except:try:# 如果以spwd查询出结果的话,就进入else,如果出错了就进入except
                stuSpwd = Stu.objects.get(spwd=stu)print(stuSpwd)except:return HttpResponse("<h1>查找失败,暂无该数据内容!</h1>")else:return render(request,'seleOne.html',{'stu':stuSpwd})else:return render(request,'seleOne.html',{'stu': stuSname})else:return render(request,'seleOne.html',{'stu': stuId})

五.在templates编写前端html页面

1.主页面

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><script>functiondelStu(sid){
            flag =confirm("确定要删除编号为:"+sid+"的数据吗?");if(flag){
                window.location.href="/stu/delStu/?sid="+sid;}}functionseleStu(){var ts=document.getElementById("Tstu").value;if(ts!=null&& ts!==""){
                window.location.href='/stu/seleStu/?Tstu='+ts;}}</script></head><body><divalign="center"><inputtype="text"id="Tstu"><inputtype="button"value="查询"onclick="seleStu()"></div>&nbsp;<tableborder="1"cellspacing="1"cellpadding="1"bgcolor="#f4a460"align="center">
{#        表头#}
        <tr><th>编号</th><th>姓名</th><th>密码</th><th>操作</th></tr>
        {% for stu in stus %}
            <tr><td>{{ stu.id }}</td><td>{{ stu.sname }}</td><td>{{ stu.spwd }}</td><td><ahref="javascript: delStu({{ stu.id }})">删除</a>&emsp;<ahref="/stu/updStu/?sid={{ stu.id }}">修改</a>&emsp;<ahref="/stu/seleOne/?sid={{ stu.id }}">详情</a>&emsp;</td></tr>
        {% endfor %}

    </table></body></html>

2.修改页面

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><style>.sbh{color: red;}</style></head><body><divalign="center"><formmethod="post"action="/stu/updStu/">
            {% csrf_token %}
            编号:<inputtype="text"name="sid"readonlyvalue="{{ stu.id }}"><spanclass="sbh">编号不可修改!</span>
            姓名:<inputtype="text"name="sname"value="{{ stu.sname }}">
            密码:<inputtype="text"name="spwd"value="{{ stu.spwd }}"><inputtype="submit"value="提交修改信息"></form></div></body></html>

3.查询and详情页面

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><style>.sbh{color: red;}</style></head><body><divalign="center"><formmethod="post"action="/stu/updStu/">
            {% csrf_token %}
            编号:<inputtype="text"name="sid"readonlyvalue="{{ stu.id }}"><spanclass="sbh">编号不可修改!</span>
            姓名:<inputtype="text"name="sname"value="{{ stu.sname }}">
            密码:<inputtype="text"name="spwd"value="{{ stu.spwd }}"><inputtype="submit"value="提交修改信息"></form></div></body></html>

六.效果图

在这里插入图片描述

七.小结

本章完成了使用Django框架对数据库的增删改查功能的实现,部分代码比较简单,并且可优化空间很大,其中比较难看的是查询功能的实现,做的比较仓促,之后会优化,感兴趣的小伙伴,动手试一下吧!
有哪里不足或者有更好的建议,欢迎留言吐槽,有哪里不懂的小伙伴,可以私信我,我会一一答复,感谢认可,感谢支持!

标签: django 数据库 python

本文转载自: https://blog.csdn.net/weixin_45539338/article/details/125685105
版权归原作者 道而起 所有, 如有侵权,请联系我们删除。

“使用Django框架实现对数据库的增删改查”的评论:

还没有评论