views.py 代码
1 from django.shortcuts import render,redirect,reverse 2 from django.db import connection 3 # 使用原生sql需引入connection模块 4 5 def get_cursor(): 6 '''获得一个数据库连接游标对象''' 7 return connection.cursor() 8 9 def index(request): 10 '''获取数据库中的图书信息,在首页展示''' 11 cursor = get_cursor() 12 cursor.execute("select id,name,author from book") 13 books = cursor.fetchall() 14 # 返回的列表嵌套元组的数据,每一个元组就是一本图书的id,name,author 15 return render(request, 'index.html', context={'books':books}) 16 17 def add_book(request): 18 '''添加新的图书信息''' 19 if request.method == 'GET': 20 # 根据判断表单提交的方式进行分类处理 21 return render(request, 'add_book.html') 22 else: 23 book_name = request.POST.get('book_name') 24 book_author = request.POST.get('book_author') 25 cursor = get_cursor() 26 cursor.execute("insert into book(name,author) values('%s','%s')" % (book_name, book_author)) 27 return redirect(reverse('index'))
urls.py 代码
1 from django.urls import path 2 from book_manager import views 3 4 urlpatterns = [ 5 path('', views.index, name='index'), 6 path('add_book/', views.add_book, name='add_book'), 7 ]
base.html 代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 <ul class="nav"> 10 <li><a href="/">首页</a></li> 11 <li><a href="{% url 'add_book' %}">发布图书</a></li> 12 </ul> 13 {% block content %} 14 {% endblock %} 15 </body> 16 </html>
index.html 代码
1 {% extends 'base.html' %} 2 3 {% block content %} 4 {% for book in books %} 5 <li>{{ forloop.counter }}</li> 6 <li>{{ book.1}}</li> 7 <li>{{ book.2}}</li> 8 {% endfor %} 9 {% endblock %}
add_book.html 代码
1 {% extends 'base.html' %} 2 {% block content %} 3 <form action="" method="post"> 4 <!-- 此次为post提交,会产生csrf错误,在setting.py中将MIDDLEWARE列表中的这句注释掉 # 'django.middleware.csrf.CsrfViewMiddleware' --> 5 <em>书名</em> 6 <input type="text" name="book_name"> 7 <br> 8 <em>作者</em> 9 <input type="text" name="book_author"> 10 <br> 11 <input type="submit" value="提交"> 12 </form> 13 {% endblock %}