Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Create Page | FrontEnd Design
Flask Intensive Course: Web Development with Python

book
Create Page

We have the option to move the form for creating a new recipe to a separate page. In doing so, we'll leave a convenient button for creating a new recipe on the recipe.html file.

To get started, let's create a fresh file named new-recipe.html. You'll find that it's going to look quite similar to what we had in recipes.html. So, go ahead and copy that piece of code and transfer it to the new file from the very beginning.

The file's name in the example below doesn't correspond to the file's name in our project.

html

new_recipe.html

copy
{% extends 'base.html' %}

{% block head %}
<title>Recipes</title>
{% endblock %}

{% block body %}
<h2>Create New Recipe: </h2>
<form action="/recipes/new/" method="Post">
Title: <input class="form-control" type="text" name="title" id="title" placeholder="Enter title"><br>
<div class="form-group">
<label for="description">Recipe description</label>
<textarea class="form-control" id="description" name="description" placeholder="Enter description" rows="3"></textarea>
</div><br>
<input type="submit" class="btn btn-success" value="Post">
</form>
{% endblock %}

Now we need to create a route first to actually render this template.

python
# main.py

@app.route("/recipes/new/", methods=["GET", "POST"])
def new_recipe():
if request.method == "POST":
recipe_title = request.form["title"]
recipe_description = request.form["description"]
new_recipe = Recipe(title=recipe_title,
description=recipe_description, author="Joey")
db.session.add(new_recipe)
db.session.commit()
return redirect("/recipes/")
else:
return render_template("new_recipe.html")

Now let's add a button to the recipe.html template for 'New recipe'.

html
<h1>All recipes</h1>
<a class="btn btn-success float-right" href="/recipe/new/">New recipe</a>

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 7

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

We use cookies to make your experience better!
some-alt