005---书籍添加和编辑的提交数据
添加和编辑两个视图函数只写了get请求渲染的页面。提交数据是post请求,所以要修改view.py。
book_add.py
1 def book_add(request): 2 if request.method == "POST": 3 title = request.POST.get('title') 4 price = request.POST.get('price') 5 pub_date = request.POST.get('pub_date') 6 publish_id = request.POST.get('pubs') 7 author_id_list = request.POST.getlist('authors') # 多选用getlist取 8 book_obj = Book.objects.create(title=title, price=price, pub_date=pub_date, publish_id=publish_id) 9 book_obj.author.add(*author_id_list) 10 return redirect('index') 11 12 pub_lt = Publish.objects.all() 13 author_lt = Author.objects.all() 14 return render(request, 'book_add.html', {"pub_list": pub_lt, "author_list": author_lt})
说明:
- 增加了post请求分支,如果是post请求,就走post里面的代码
- 获取前端form传来的数据,request.POST.get(),因为author是多选,有多个值所以用getlist
- 在数据库中创建一条书籍记录。绑定多对多关系,book_obj.author.add(*author_id_list)
- 重定向到inex页面。因为添加了别名,所以可以这样使用
book_edit.py
1 def book_edit(request, book_id): 2 book = Book.objects.filter(pk=book_id).first() 3 if request.method == "POST": 4 title = request.POST.get('title') 5 price = request.POST.get('price') 6 pub_date = request.POST.get('pub_date') 7 publish_id = request.POST.get('pubs') 8 Book.objects.filter(pk=book_id).update(title=title, price=price, pub_date=pub_date, publish_id=publish_id) 9 author_id_list = request.POST.getlist('authors') # 多选用getlist取 10 11 # 多对多更新 12 book.author.set(author_id_list) 13 return redirect('index') 14 pub_lt = Publish.objects.all() 15 authors = Author.objects.all() 16 17 return render(request, 'book_edit.html', {"book": book, "pub_list": pub_lt, "author_list": authors})
说明:
- 基本和添加的逻辑一样,只是入库的时候不一样。
更改完,我们的添加和编辑就能生效了。但是代码一样的多啊,,,好多重复的,还有更高级的用法:
你看看就行了,这有就入库了。
1 def book_add(request): 2 if request.method == 'POST': 3 form = BookForm(request.POST) 4 if form.is_valid(): 5 form.save() 6 return redirect('/books/') 7 form = BookForm() 8 return render(request, 'book_add.html', locals()) 9 10 11 def book_edit(request, edit_book_id): 12 book_obj = Book.objects.filter(pk=edit_book_id).first() 13 if request.method == 'POST': 14 form = BookForm(request.POST, instance=book_obj) 15 if form.is_valid(): 16 form.save() 17 return redirect('/books/') 18 form = BookForm(instance=book_obj) 19 return render(request, 'book_edit.html', locals())