Sourabh
Sourabh

Reputation: 33

Save the passed value from python in html select tag form

I am passing a string value to select tag in html form and its working properly. But when I load the page again or run the script again, the previously passed values are not shown in drop down list.

In html form, I am passing value like this:

<option value="{{x}}">{{x}}</option>

In python:

x = "Example" 
return render_template('example.html', x=x)

can anyone please let me know how to save this value so that it is available for selection in drop down list.

Thanks in advance!

Upvotes: 0

Views: 804

Answers (2)

Arpit Omprakash
Arpit Omprakash

Reputation: 118

The way I see it, there are three possible ways to achieve this:

  1. Use session variables/cookies

Try saving the option list as a variable in a cookie on the client side. This will also work even if you reload your python script. Here's a link to get you started: https://testdriven.io/blog/flask-sessions/

  1. Use forwarding url values

You can use the url as a place to store values for the options list. For example, the following coarse code logic does the same (just modifying the code provided by HRSArgyropoulos):

# example.html
 {% if options %}
    <select name="foo" id="foo">
    {% for option in options %}
        <option value="{{ option }}">{{ option }}</option>
        <a href={{url_for('xyz', options=options_list, new_option=option)}}></a>
    {% endfor %}
    </select>
{% endif %}

# app.py
@app.route("/xyz/<str:options_list>/<str:new_option>)", methods=('get', 'post'))
def xyz(options_list, new_option)
    options_list.append(new_option)
    return render_template('example.html', options=options_list)
  1. Use database

This is pretty straight forward, just use a sqlite database on the backend to store values as a list. Here's a link to get you started: https://flask.palletsprojects.com/en/3.0.x/patterns/sqlite3/

Upvotes: 0

HRSArgyropoulos
HRSArgyropoulos

Reputation: 21

You could set a list, append new option values in it and then pass the list to your html template. Something like this;

# app.py
    optionsList = []
    optionsList.append('Example')
    optionsList.append('Example2')
    return render_template('example.html', options=optionsList)

# example.html
    {% if options %}
        <select name="foo" id="foo">
        {% for option in options %}
            <option value="{{ option }}">{{ option }}</option>
        {% endfor %}
        </select>
    {% endif %}

Upvotes: 1

Related Questions