1

Similar questions have been asked but I can't get it to work for me, I'm not sure what the issue is so I thought I'd ask again incase anyone has some pointers.

I am trying to pass a function in Flask dependent on which button is pressed on the webpage. These are the HTML buttons:

<div class="row">
        <h2>Your Wordclouds:</h2>
        <input type="submit" name="submit_button" value="Positive" class='btn'> 
        <input type="submit" name="submit_button" value="Negative" class='btn'>
        {{value}}
</div>

My function:

@app.route('/insight', methods=['GET', 'POST'])
def wordcloud():
    if request.method == 'POST':
        if request.form['submit_button'] == "Positive":
            mysql.connection.cursor()
            query = ("SELECT journal_entry FROM journals WHERE sentiment = 'positive'")
            df = pd.read_sql(query, mysql.connection)
            journal_entry = df['journal_entry']
            long_string = (''.join(str(journal_entry.tolist())))
            # Create WordCloud object
            wordcloud = WordCloud(background_color="white", max_words=4500, contour_width=6, contour_color='blue')
            # Generate the cloud
            wordcloud.generate(long_string)
            wordcloud.to_file("wordcloud.png")
            filename = Image.open("wordcloud.png")
            main_themes = filename.show()
            

        elif request.form['submit_button'] == "Negative":
            mysql.connection.cursor()
            query = ("SELECT journal_entry FROM journals WHERE sentiment = 'negative'")
            df = pd.read_sql(query, mysql.connection)
            journal_entry = df['journal_entry']
            long_string = (''.join(str(journal_entry.tolist())))
            # Create WordCloud object
            wordcloud = WordCloud(background_color="white", max_words=500, contour_width=6, contour_color='blue')
            # Generate the cloud
            wordcloud.generate(long_string)
            wordcloud.to_file("wordcloud.png")
            filename = Image.open("wordcloud.png")
            main_themes = filename.show()

         return render_template('insight.html', value=main_themes)
        
    else:
        return render_template('insight.html')

The functions work fine individually when I use the GET method, and the wordcloud image is automatically generated on page load. But since there are options I only want to trigger the generation on click.

Any help much appreciated

LilRi
  • 49
  • 1
  • 6

1 Answers1

1

This seems to be answered already - two buttons form

Here is some code specific to your problem:

1. Using request.form's .get method:
(I personally prefer this one because you don't depend on input values, which can change overtime)

insight_1.html:

<form action="{{ url_for('wordcloud_1') }}" method="POST">
    <input type="submit" name="submit_button_1" value="Positive">
    <input type="submit" name="submit_button_2" value="Negative">
</form>
{% if value %}
    {{value}}
{% endif %}

main.py:

@app.route('/insight_1', methods=['GET', 'POST'])
def wordcloud_1():
    # Default value
    value = None

    if request.method == 'POST':
        submit_button_1 = request.form.get('submit_button_1', None)
        submit_button_2 = request.form.get('submit_button_2', None)

        if submit_button_1:
            # Do your stuff
            value = 'Some result if submit_button_1 was pressed'
        elif submit_button_2:
            # Do your stuff
            value = 'Some result if submit_button_2 was pressed'

    return render_template(
        'insight_1.html',
        value=value,
    )

2. Using the same name attribute for both submit elements:

insight_2.html:

<form action="{{ url_for('wordcloud_2') }}" method="POST">
    <input type="submit" name="submit_button" value="Positive">
    <input type="submit" name="submit_button" value="Negative">
</form>
{% if value %}
    {{value}}
{% endif %}

main.py:

@app.route('/insight_2', methods=['GET', 'POST'])
def wordcloud_2():
    # Default value
    value = None

    if request.method == 'POST':
        submit_button = request.form['submit_button']

        if submit_button == 'Positive':
            # Do your stuff
            value = 'Some result if submit_button_1 was pressed'
        elif submit_button == 'Negative':
            # Do your stuff
            value = 'Some result if submit_button_2 was pressed'

    return render_template(
        'insight_2.html',
        value=value,
    )
barni
  • 436
  • 3
  • 8