def add_book(): form = BookForm(request.form) form.authors.choices = sorted([(a.id, a.name) for a in Author.query.all()], key=lambda author: author[1].split()[-1]) if request.method == 'POST' and form.validate(): book = Book(form.name.data) for id in form.authors.data: book.authors.append(Author.query.get(id)) db_session.add(book) db_session.commit() flash('The book was added to the Library.') return redirect(url_for('view_book', id=book.id)) return render_template('library/add_book.html', form=form)
def edit_book(id): error = None book = Book.query.get(id) if not book: error = 'Sorry, we don\'t have the book with id {0}.'.format(id) form = BookForm(request.form, obj=book) form.authors.choices = sorted([(a.id, a.name) for a in Author.query.all()], key=lambda author: author[1].split()[-1]) if request.method == 'POST' and form.validate(): book.name = form.name.data book.authors = [] for id in form.authors.data: book.authors.append(Author.query.get(id)) db_session.add(book) db_session.commit() return redirect(url_for('view_book', id=book.id)) form.authors.data = [a.id for a in book.authors] return render_template('library/edit_book.html', form=form, book=book, error=error)