Monika Nishad
Monika Nishad

Reputation: 181

Unable to add list to session in flask

I have simple input field where user is adding note.. and what ever note user is adding it will be displayed above in the list.. and m trying to store in a session in flask

This is my flask code

from flask import Flask, render_template, request, session
from flask_session import Session

app = Flask(__name__)

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


@app.route("/", methods=["GET", "POST"])
def index(): 
    if session.get("notes") is None:
        session["notes"]=[]

    if request.method == "POST":
        note = request.form.get("note")
        session["notes"].append(note)

    return render_template("session-index.html", notes=session["notes"])

if __name__ == "__main__":
    app.run(debug=True)

And this is my html page

{% extends "inherit-layout.html" %}
{% block heading %}
    Form Page
{% endblock %}

{% block body %}

    <ul>
        {% for note in notes %}
        <li>{{ note }}</li>
        {% endfor %}
    </ul>

    <form action="{{ url_for('index') }}" method="POST">

        <input type="text" name="note" placeholder="Enter Note Here">
        <button type="submit">Add Note</button>

    </form>

{% endblock %}

What currently happening is when m adding note for second time it is replacing previous one in the list.

Upvotes: 1

Views: 870

Answers (1)

Ancoor D Banerjee
Ancoor D Banerjee

Reputation: 437

from flask import *


app = Flask(__name__)

app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SECRET_KEY'] = "asddaffffa"



@app.route("/", methods=["GET", "POST"])
def index(): 

    if session.get("notes") is None:
        session["notes"]=[]

    if request.method == "POST":
        note = request.form.get("note")
        list = session["notes"]
        list.append(note)
        session["notes"] = list

    return render_template("session-index.html", notes=session["notes"])

if __name__ == "__main__":
    app.run(debug=True)

This should work..

Upvotes: 1

Related Questions