I want to check if a value, for example the ‘name’ value, exists in a session in a Flask application I made, but it’s not working.
Python:
@app.route("/add/<string: name>")
def add(name):
session["list"].append(name)
return "Successful"
@app.route("/list
def list():
cursor=mysql.connection.cursor()
query="Select * From data where id=1"
cursor.execute(query)
data=cursor.fetchone()
return render_template("list.html",data=data)
HTML:
{% if data.name in session["list"] %}
There is
{% else %}
None
{% endif %}
Even if the data.name value is in the session, it goes into the else block
2
Answers
1.session is a
dict
. So if you want the value of a key of thisdict
to be alist
, you should initialise it. (session['list'] = []
)2.The closing quote is missing in the route of
/list
(@app.route("/list")
)3.Make sure to import session and configure the secret_key(probably you would have imported, but not shown in the code)
4.While fetching from database, if
data
isdict
, you should mention{% if data['name'] in session["list"] %}
in your jinja2 code. Ifdata
is object, you should mentiondata.name
like{% if data.name in session["list"] %}
. Ensure whether it is used properly.5.To know if value is inside session, add error handling in the code
If you save a list within the session and do not make a new assignment but add an item to the list, it is necessary to mark the session as modified. This applies to all changes to mutable structures.