新增出版社
前端代码
前端publisher_add页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
出版社名称: <input type="text" name="pub_name"> <span>{{ error }}</span>
<button>提交</button>
</form>
</body>
</html>
前端publisher_list页面代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/publisher_add/">新增出版社</a>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>id</th>
<th>出版社名称</th>
</tr>
</thead>
<tbody>
{% for i in publisher_list %} <!-- for循环来显示出版社 -->
<tr>
<td>{{ forloop.counter }}</td> <!-- 循环计数 -->
<td>{{ i.id }}</td> <!-- 取出id -->
<td>{{ i.name }}</td> <!-- 取出出版社名字 -->
</tr>
{% endfor %} <!-- 结束for循环 -->
</tbody>
</table>
</body>
</html>
后端代码
view.py代码如下:
from django.shortcuts import render, redirect
from app01 import models
# Create your views here.
def publisher_list(request):
obj = models.Publisher.objects.all() # 获取所有对象
return render(request, 'publisher_list.html', {'publisher_list': obj}) # {'publisher_list': obj}是模板,可以传递给前端页面。
def publisher_add(request):
if request.method == "POST": # 如果是POST请求
pub_name = request.POST.get('pub_name') # 获取出版社的名称
if not pub_name:
return render(request, 'publisher_add.html', {'error': "出版社名字不能为空"})
if models.Publisher.objects.filter(name=pub_name):
return render(request, 'publisher_add.html', {'error': "出版社已经存在"})
models.Publisher.objects.create(name=pub_name) # 增加出版社,使用create方法
return redirect('/publisher_list/') # 增加完成以后,跳转到获取所有出版社页面
return render(request, 'publisher_add.html') # 默认返回增加页面。
urls.py设置路由如下:
"""bookmanager URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('publisher_list/', views.publisher_list),
path('publisher_add/', views.publisher_add),
]
运行效果如下所示: