def recipes_create(): form = RecipeForm(request.form) form.recipe_id = -1 # Checking that the form passes validations if not form.validate(): return render_template("recipes/new.html", form=form) # Adding the new recipe name = form.name.data.strip() name = (name[0].upper() + name[1:]) newRecipe = Recipe(name) newRecipe.instruction = form.instruction.data newRecipe.preptime = form.preptime.data newRecipe.account_id = current_user.id # Separating and adding tags tagsString = form.tags.data.strip() tags = tagsString.split(',') Tag.add_tags(tags, newRecipe) # Commiting changes db.session().add(newRecipe) db.session().commit() # Ingredients need recipe ID, # so they are added only after the recipe is added addedRecipe = Recipe.query.filter(Recipe.name == newRecipe.name).first() ingredients = form.ingredients.data.splitlines() Ingredient.add_ingredients(ingredients, addedRecipe) return redirect(url_for("recipes_index"))
def recipe_edit(recipe_id): # POST is not accepted if current user is not the creator of the recipe # or an administrator recipe = Recipe.query.get(recipe_id) if ((recipe.account_id is not current_user.get_id()) and (current_user.get_role() != 'admin')): return abort(401) form = RecipeEditForm(request.form) # If form does not pass validations, # a new faulty form is created to be shown along with error messages, # but never put to the database if not form.validate(): faultyRecipe = Recipe(request.form['name']) faultyRecipe.id = recipe_id faultyRecipe.instruction = request.form['instruction'] faultyRecipe.preptime = request.form.get("preptime") faultyIngredients = request.form.get("ingredients") faultyTags = request.form.get("tags") return render_template("recipes/edit.html", recipe=faultyRecipe, form=form, tags=faultyTags, ingredients=faultyIngredients) # Fetching and editing the recipe changedRecipe = Recipe.query.get(recipe_id) name = request.form.get("name").strip() name = name[0].upper() + name[1:] changedRecipe.name = name changedRecipe.instruction = request.form.get("instruction") changedRecipe.preptime = request.form.get("preptime") # Add tags for the recipe tags = form.tags.data.split(',') Tag.add_tags(tags, changedRecipe) db.session().commit() ingredients = request.form.get("ingredients").splitlines() Ingredient.add_ingredients(ingredients, changedRecipe) return redirect(url_for("recipes_index"))