Pav Sidhu
Pav Sidhu

Reputation: 6944

Issues sending and receiving a GET request using Flask

I'm having issues with correctly sending and receiving a variable with a GET request. I cannot find any information online either. From the HTML form below, you can see I'm sending the value of 'question' but I'm also receiving 'topic' from a radio button in the form (though the code is for that is not below).

I want to send 'topic' using POST but use GET for 'question'. I'm aware that the form method is POST though I'm not sure how to cater for both POST and GET.

HTML Form:

<form method="POST" action="{{ url_for('topic', question=1) }}">

My second issue is that I'm unsure how to receive 'topic' AND 'question' from the form. I've managed to receive 'topic' as seen below but I'm not quite sure how to receive 'question'. Preferably it would be better for the URL to be like so:

www.website.com/topic/SomeTopic?question=1

For the code below, I found online that request.args[] is used for receiving GET requests though I'm not sure if it is correct.

Flask:

@app.route('/topic/<topic>', methods=['POST', 'GET'])
def questions(topic):
    question = request.args['questions']
    return render_template('page.html')

The question is

  1. How do I send two variables from a form using GET and POST for different variables at the same time.
  2. How would I go about receiving both variables?

Upvotes: 1

Views: 769

Answers (1)

junnytony
junnytony

Reputation: 3515

The short answer to your question is that you can't send both GET and POST using the same form.

But if you want your url to look like you specified:

www.website.com/topic/SomeTopic?question=1

then you're almost there. First you will need to already know the name of the topic as you have to specify that in your call to url_for() for the questions url.

<form method="GET" action="{{ url_for('questions', topic_name="cars") }}">
# Your url will be generated as www.website.com/topic/cars

flask

# Note that I changed the variable name here so you can see how
# its related to what's passed into url_for
@app.route('/topic/<topic_name>')
def questions(topic_name):
    question = request.args['question']
    return render_template('page.html')

Now when you submit your form, your input will be sent as a GET, an asumming you have an input field with the name question you'll be able to get the value of that field.

Upvotes: 1

Related Questions