I'm new to Flask and Jinja2 and HTML templates and I'm trying to learn how to pass information back and forth between the controller and the views. Basically, I have a calendar of events. Each event name is a hyperlink that uses url_for to go to a view with more information about that event. But although I can easily pass a list of custom Event objects into the HTML file, I don't know how to have the selected Event object returned to the controller. From what I can tell, the object is being turned into a string. Simplified code below.
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
class Event(object):
def __init__(self, name, date):
self.name = name
self.date = date
events = [Event('event1', '2020-04-11')]
@app.route('/')
def index():
return render_template('index.html', events=events)
@app.route('/event/<event>')
def event(event):
return render_template('event.html', event=event)
index.html
<!DOCTYPE html>
<html>
<body>
{% for event in events %}
<a href={{ url_for('event', event=event) }}>{{ event.name }}</a>
{% endfor %}
</body>
</html>
event.html
<!DOCTYPE html>
<html>
<body>
<p>{{ event.name }} {{ event.date }}</p>
</body>
</html>
Clicking on the event brings me to a blank page, presumably because event.html is trying to get attributes of a string object that don't exist.
When passing the python object into the view is so simple, it seems like there's probably an equally simple way to get it back from the view. Please enlighten me!