Django(六)实战2:向数据库添加,删除数据、重定向写法、重定向简写

一、向数据库添加图书数据

【上接】https://blog.csdn.net/u010132177/article/details/103831173

1)首先开启mysql服务,并运行项目

启动mysql服务:
net start mysql80

启动项目:
py manage.py runserver

2)在templates/app1/book.html添加按钮

【1】添加新书按钮 <a href="/detail/{{book.id}}">
hre里的斜杠/默认一定要加上,否则其它页面,如下面的delete中,会导致定向到 /index/delete/不存在 的页面中去

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍页面</title>
</head>
<body>
本站的图书有:<br/>
<ul>
    {% for book in books %}
        <!--通过href属性,把book的id做为参数传给详情页,进而查询对应英雄信息-->
        <li><a href="/detail/{{book.id}}"> {{book.btitle}}</a>:{{book.bpub_date}}</li>
    {%empty%}
    	暂时没有图书!!!
    {% endfor %}
</ul>
<!--【1】添加新书按钮-->
<a href="/addInfo">添加一本三国书</a><br/>
</body>
</html>

3)app1/views.py 编写向数据表中增加书籍函数

【0】引入返回请求模块、重新定向模块
【0.1】引用时间模块
【1】添加书籍函数:创建bookinfo对象,并添加一本书
【2.0】成功 return HttpResponse('数据添加成功')
【2】添加成功后重新定向到页面:http://127.0.0.1:8000/books/

from django.shortcuts import render
from app1.models import BookInfo #从模型下导入bookinfo数据模型
from django.http import HttpResponse,HttpResponseRedirect #【0】引入返回请求模块、重新定向模块
from datetime import date #【0.1】引用时间模块

def index(request):
    '''app1应用:首页'''
    context={} #定义1个字典
    context['hello']='hello world!!!' #向字典写一个键:值(hello:'hello world!!')
    context['wa']='wawawawawahahahaha!'
    context['list']=list(range(1,10)) #定义一个字典值为一个列表,list为把内容转换为列表
    return render(request,'app1/index.html',context) #返回:把context渲染到app1/index.html的模板文件

def books(request):
    '''app1应用:图书列表页'''
    books=BookInfo.objects.all()#从数据库获取图书对象列表
    return render(request,'app1/book.html',{'books':books})#把获取到的图书对象赋值给books键。【注意】键'books'必须要加引号

def detail(request,bookId):# bookId为接收urls.py中指定的参数,来源页templates/app1/book.html
    '''app1应用:图书详情页,显示英雄信息'''
    book=BookInfo.objects.get(pk=bookId) #查询主键为url中传过来的参数Id。或写成:id=bookId
    heros=book.heroinfo_set.all() #关联查询:查询对应书的所有英雄信息
    return render(request,'app1/detail.html',{'book':book,'heros':heros}) #把参数渲染到detail页面去


def addInfo(request):
    '''添加新书到bookinfo表里'''
    #【1】创建bookinfo对象,并添加一本书
    b=BookInfo()
    b.btitle='水浒传'
    b.bpub_date=date(1989,9,9)
    b.save()

    #return HttpResponse('数据添加成功')
    #【2】添加成功后重新定向到页面:http://127.0.0.1:8000/books/
    return HttpResponseRedirect('/books')

4)添加app1/urls.py信息

添加三国书

from django.urls import path,re_path
from . import views

urlpatterns=[
    path('app1/',views.index),
    path('books/',views.books),

    # 书详情页,通过url接收参数2种写法以下两种都可:
    # path(r"detail/<int:bookId>",views.detail), #参数用尖括号包起来<>
    re_path(r"^detail/(d+)",views.detail), #参数必须要带括号

    path('addInfo/',views.addInfo),#添加三国书
]

5)效果:http://127.0.0.1:8000/books/

点击后即向数据库添加一本书,添加成功后,重定向回books页面。
在这里插入图片描述

二、删除对应图书

1) templates/app1/book.html

关键行:<a href="/delete/{{book.id}}">删除</a>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍页面</title>
</head>
<body>
本站的图书有:<br/>
<ul>
    {% for book in books %}
        <!--通过href属性,把book的id做为参数传给详情页,进而查询对应英雄信息-->
        <li><a href="/detail/{{book.id}}"> {{book.btitle}}</a>:{{book.bpub_date}}-----<a href="/delete/{{book.id}}">删除</a> </li>
    {%empty%}
    	暂时没有图书!!!
    {% endfor %}
</ul>
<!--添加新书按钮-->
<a href="/addInfo">添加一本书</a><br/>
</body>
</html>

2 )配置App1/urls.py

关键:path(r'delete/<int:bid>',views.deleteInfo), #删除对应图书
注意:path()间逗号一定别忘记写,否则可能导致未知错误

from django.urls import path,re_path
from . import views

urlpatterns=[
    path('app1/',views.index),
    path('books/',views.books),

    # 书详情页,通过url接收参数2种写法以下两种都可:
    # path(r"detail/<int:bookId>",views.detail), #参数用尖括号包起来<>
    re_path(r"^detail/(d+)",views.detail), #参数必须要带括号

    path('addInfo/',views.addInfo), #添加三国书

    path(r'delete/<int:bid>',views.deleteInfo), #删除对应图书
]

3)app1/views.py编写删除函数

删除bookinfo id=bid的书籍

from django.shortcuts import render
from app1.models import BookInfo #从模型下导入bookinfo数据模型
from django.http import HttpResponse,HttpResponseRedirect #【0】引入返回请求模块、重新定向模块
from datetime import date #【0.1】引用时间模块

def index(request):
    '''app1应用:首页'''
    context={} #定义1个字典
    context['hello']='hello world!!!' #向字典写一个键:值(hello:'hello world!!')
    context['wa']='wawawawawahahahaha!'
    context['list']=list(range(1,10)) #定义一个字典值为一个列表,list为把内容转换为列表
    return render(request,'app1/index.html',context) #返回:把context渲染到app1/index.html的模板文件

def books(request):
    '''app1应用:图书列表页'''
    books=BookInfo.objects.all()#从数据库获取图书对象列表
    return render(request,'app1/book.html',{'books':books})#把获取到的图书对象赋值给books键。【注意】键'books'必须要加引号

def detail(request,bookId):# bookId为接收urls.py中指定的参数,来源页templates/app1/book.html
    '''app1应用:图书详情页,显示英雄信息'''
    book=BookInfo.objects.get(pk=bookId) #查询主键为url中传过来的参数Id。或写成:id=bookId
    heros=book.heroinfo_set.all() #关联查询:查询对应书的所有英雄信息
    return render(request,'app1/detail.html',{'book':book,'heros':heros}) #把参数渲染到detail页面去


def addInfo(request):
    '''添加新书到bookinfo表里'''
    #【1】创建bookinfo对象,并添加一本书
    b=BookInfo()
    b.btitle='水浒传'
    b.bpub_date=date(1989,9,9)
    b.save()

    #return HttpResponse('数据添加成功')
    #【2】添加成功后重新定向到页面:http://127.0.0.1:8000/books/
    return HttpResponseRedirect('/books')


def deleteInfo(request,bid):
    '''删除bookinfo id=bid的书籍'''
    #根据传过来的bid查到对应书籍
    b=BookInfo.objects.get(id=bid) #也可(主键)pk=bid
    b.delete()

    return HttpResponseRedirect('/books')

效果:http://127.0.0.1:8000/books/

点删除,删除对应图书,并重定向回books页面
在这里插入图片描述

三、重定向简写

关键:from django.shortcuts import render,redirect #引入重定向简写模块
使用:return redirect('/books') #【2】简写重定向

app1/views.py

from django.shortcuts import render,redirect #引入重定向简写模块
from app1.models import BookInfo #从模型下导入bookinfo数据模型
from django.http import HttpResponse,HttpResponseRedirect #引入返回请求模块、重新定向模块
from datetime import date # 引用时间模块

def index(request):
    '''app1应用:首页'''
    context={} #定义1个字典
    context['hello']='hello world!!!' #向字典写一个键:值(hello:'hello world!!')
    context['wa']='wawawawawahahahaha!'
    context['list']=list(range(1,10)) #定义一个字典值为一个列表,list为把内容转换为列表
    return render(request,'app1/index.html',context) #返回:把context渲染到app1/index.html的模板文件

def books(request):
    '''app1应用:图书列表页'''
    books=BookInfo.objects.all()#从数据库获取图书对象列表
    return render(request,'app1/book.html',{'books':books})#把获取到的图书对象赋值给books键。【注意】键'books'必须要加引号

def detail(request,bookId):# bookId为接收urls.py中指定的参数,来源页templates/app1/book.html
    '''app1应用:图书详情页,显示英雄信息'''
    book=BookInfo.objects.get(pk=bookId) #查询主键为url中传过来的参数Id。或写成:id=bookId
    heros=book.heroinfo_set.all() #关联查询:查询对应书的所有英雄信息
    return render(request,'app1/detail.html',{'book':book,'heros':heros}) #把参数渲染到detail页面去


def addInfo(request):
    '''添加新书到bookinfo表里'''
    #【1】创建bookinfo对象,并添加一本书
    b=BookInfo()
    b.btitle='水浒传'
    b.bpub_date=date(1989,9,9)
    b.save()

    #return HttpResponse('数据添加成功')
    #【2】添加成功后重新定向到页面:http://127.0.0.1:8000/books/
    return HttpResponseRedirect('/books')


def deleteInfo(request,bid):
    '''删除bookinfo id=bid的书籍'''
    #根据传过来的bid查到对应书籍
    b=BookInfo.objects.get(id=bid) #也可(主键)pk=bid
    b.delete()

    #return HttpResponseRedirect('/books')
    return  redirect('/books') #【2】简写重定向

效果同上

原文地址:https://www.cnblogs.com/chenxi188/p/12176663.html