锋哥原创的Python Web开发 Django5视频教程:
我们结合案例先实现下;
我们在views.py里先定义preUpdate方法,修改预处理,根据id获取图书信息,以及获取图书类别列表;
def preUpdate(request, id):
"""
预处理,修改操作
:param request:
:return:
"""
print("id:", id)
book = BookInfo.objects.get(id=id)
print(book)
bookTypeList = BookTypeInfo.objects.all()
print(bookTypeList)
content_value = {"title": "图书修改", "bookTypeList": bookTypeList, "book": book}
return render(request, 'book/edit.html', context=content_value)
urls.py里加下映射:
path('book/preUpdate/<int:id>', helloWorld.views.preUpdate),
book/list.html修改下,加下修改操作链接:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h3>{{ title }}</h3>
<a href="/book/preAdd">添加</a><br/><br/>
<table border="1">
<tr>
<th>编号</th>
<th>图书名称</th>
<th>价格</th>
<th>出版日期</th>
<th>图书类别</th>
<th>操作</th>
</tr>
{% for book in bookList %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.bookName }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publishDate | date:'Y-m-d' }}</td>
<td>{{ book.bookType.bookTypeName }}</td>
<td>
<a href="/book/preUpdate/{{ book.id }}">修改</a>
</td>
</tr>
{% endfor %}
</table>
</body>
</html>
新建编辑页面edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h3>{{ title }}</h3>
<form action="/book/update" method="post">
{% csrf_token %}
<table>
<tr>
<td>图书名称:</td>
<td>
<input type="text" name="bookName" value="{{ book.bookName }}">
</td>
</tr>
<tr>
<td>出版日期:</td>
<td>
<input type="text" name="publishDate" value="{{ book.publishDate | date:'Y-m-d' }}">
</td>
</tr>
<tr>
<td>图书类别:</td>
<td>
<select name="bookType_id">
{% for bookType in bookTypeList %}
<option value="{{ bookType.id }}"
{% if book.bookType.id == bookType.id %}selected{% endif %}>
{{ bookType.bookTypeName }}
</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>图书价格:</td>
<td>
<input type="text" name="price" value="{{ book.price }}">
</td>
</tr>
<tr>
<td colspan="2">
<input type="hidden" name="id" value="{{ book.id }}">
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
</html>
再写一个update方法,保存图书信息
def update(request):
"""
图书修改
:param request:
:return:
"""
book = BookInfo()
book.id = request.POST.get("id")
book.bookName = request.POST.get("bookName")
book.publishDate = request.POST.get("publishDate")
book.bookType_id = request.POST.get("bookType_id")
book.price = request.POST.get("price")
book.save()
return bookList(request)
urls.py里再加下映射:
path('book/update', helloWorld.views.update),
我们来测试下,浏览器输入:http://127.0.0.1:8000/book/list
我们点修改,修改id是5的图书,
修改信息后,点提交;
测试成功!