def update_item(): """ Update the requested item. """ # Get the category and check if it's exist or fail to 404 page if not category = Category.find_or_fail(request.form['category_id']) # Get the item and check if it's exist or fail to 404 page if not item = Item.find_or_fail(request.form['item_id']) # Make sure the current user is authorized or not if not item.user or item.user.id != current_user.id: return current_app.login_manager.unauthorized() # The below is for validate the unique slug, if it # was exists before, then the ORM will not fall to # the ModelNotFound exception and the code will # continue flashing the error message to the user. # Otherwise, if the slug is not exists, then the # request is completely valid and the ORM will # going to fall to the ModelNotFound exception # then save the new Item try: # Get the current item slug before it changing using ORM mutator old_item_slug = item.slug item.title = request.form['title'] item.description = request.form['description'] # Associate the new item with the category item.category().associate(category) # Associate the new item to the current user item.user().associate(current_user) # Get the item and check if it's exist or fail to 404 page if not Item.where('slug', item.slug).first_or_fail() # if the current slug is the same as requested then throw # to the ModelNotFound Exception and save the current item if item.slug == old_item_slug: raise ModelNotFound(item.__class__) flash('The title seems similar to another' ' title, please choose another one.') return render_template('items/edit.html', categories=Category.all(), item=item) except ModelNotFound: # Save the item item.save() return redirect( url_for('view_item', category_slug=category.slug, item_slug=item.slug))
def destroy_item(): """ Delete the item. """ # Get the item and check if it's exist or fail to 404 page if not item = Item.find_or_fail(request.form['item_id']) # Make sure the current user is authorized or not if not item.user or item.user.id != current_user.id: return current_app.login_manager.unauthorized() # Get the category slug before the item goes to delete category_slug = item.category.slug # Delete the item item.delete() return redirect(url_for('list_items', category_slug=category_slug))