I try to reference another page from this page
<html>
<head>
</head>
<body>
<header>
<h1>Restaurants<h1>
</header>
{% for i in restaurants %}
<h5>
<a href= "*">
{{i.name}}
</a>
   
<a href = "*"> Edit </a>  
<a href = "*"> Delete </a>
</h5>
{% endfor %}
<a href = {{url_for('newRestaurant', restaurant_id = restaurant_id)}}> Create new restaurant </a>
</body>
</html>
Here is my web server from where I manage the routes:
from flask import Flask, render_template, request, redirect, url_for, flash
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
# Show all restaurants
.....
#Create new restaurants
@app.route('/restaurant/<int:restaurant_id>/new', methods = ['GET','POS'])
def newRestaurant(restaurant_id):
if request.method == 'POST':
new_Restaurant = Restaurant(name = request.form['new_restaurant_name'], restaurant_id = restaurant_id)
session.add(new_Restaurant)
session.commit()
#return "This page will be for making a new restaurant"
flash("new restaurant create")
return redirect(url_for('restaurants', restaurant_id = restaurant_id))
else:
return render('newRestaurant.html', restaurant_id = restaurant_id)
Here I am trying to route to my create restaurant page :
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
You don't send anything to restaurant_id
in the jinja template:
{{url_for('newRestaurant', restaurant_id = restaurant_id)}}
the second restaurant_id
is not defined because you're not sending any value through it to the template.
You should send a number from your newRestaurant
function.
For example (and this is only a simple example), you could verify if there is no row in the Restaurant table and if it isn't you initiate restaurant_id = 1
:
EDITED
@app.route('/restaurant/<int:restaurant_id>', methods = ['GET','POST'])
def newRestaurant(restaurant_id):
if request.method == 'POST':
.............
else:
restaurants = session.query(Restaurant).all()
if not restaurants:
restaurant_id = 1
else:
nr_restaurants = session.query(Restaurant).count()
restaurant_id = int(nr_restaurants) + 1
return render_template('newRestaurant.html', restaurant_id = restaurant_id)
now you are sending a number to the template through restaurant_id
variable and you can use it there.