def view_item_post(id): """handle post requests for an item""" if not check_active_session(login_session) and "user_info" not in login_session.keys(): flash("Error: invalid session") return redirect("/item/") item = session.query(Item).get(id) if not item: flash("Error: Item not found") return redirect("/item/") # ensure logged in user owns the item if not login_session["user_info"]["user_id"] == item.user_id: flash("Error: You are not logged in") return redirect("/login/") edit_form = ItemForm() if edit_form.validate_on_submit(): # update image if included item.image = push_image(session, edit_form.image.data.filename) if item.category != edit_form.category.data: # update category if changed item.category = update_category(edit_form.category.data, session, item.category) # update item item.name = edit_form.name.data item.description = edit_form.description.data item.updated_date = datetime.utcnow() session.add(item) # save image near commit edit_form.image.data.save(os.path.join(app.config["UPLOAD_DIR"], item.image.filename)) session.commit() flash("%s updated." % item.name) return redirect("/item/%s/" % item.id) del_form = ItemDeleteForm() if del_form.validate_on_submit(): # remove unused category pop_category(item.category, session) # remove item session.delete(item) session.commit() flash("%s deleted" % item.name) return redirect("/item/")
def view_item_new_post(): """handle new item requests""" # ensure user is logged in and session is active if not check_active_session(login_session) and "user_info" not in login_session.keys(): flash("Error: you are not logged in.") return redirect("/login/") form = ItemForm() if form.validate_on_submit(): # add category if needed try: new_cat = session.query(Category).filter_by(name=form.category.data).one() except db.NoResultFound: new_cat = Category(name=form.category.data) session.add(new_cat) # create db image new_image = push_image(session, form.image.data.filename) # create item new_item = Item( name=form.name.data, category=new_cat, description=form.description.data, created_date=datetime.utcnow(), updated_date=datetime.utcnow(), user_id=login_session["user_info"]["user_id"], image=new_image, ) # update db session.add(new_item) session.commit() # save image near commit form.image.data.save(os.path.join(app.config["UPLOAD_DIR"], new_image.filename)) flash("%s added to items." % new_item.name) return redirect("/item/") else: flash("Error: bad form %s" % form.errors) return redirect("/item/new/")