0

This is an incredibly simple question and I am ashamed to be asking it here, but I have been Googling answers for the past 3 hours with no results.

Basically, I am trying to send information using an HTML form and accept that information with a Flask python script. The problem is whenever I try to submit the form, it says Cannot POST path/form.html

The HTML Form:

<form method="post"> 
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="fname" placeholder="firstname">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lname" placeholder="lastname">
<button type="submit">Login</button>

The Python/Flask Code:

from flask import Flask, request, render_template  

# Flask constructor
app = Flask(__name__)

# A decorator used to tell the application
# which URL is associated function
@app.route('/', methods =["GET", "POST"])
def gfg():
    if request.method == "POST":
       # getting input with name = fname in HTML form
       first_name = request.form.get("fname")
       # getting input with name = lname in HTML form
       last_name = request.form.get("lname")
       return "Your name is "+first_name + last_name
    return render_template("form.html")

if __name__=='__main__':
   app.run()

I know this should be simple but web development is not my forte and this is really out of my element. Is this a server problem? Thank you in advance.

6
  • 2
    Does this help? stackoverflow.com/questions/11556958/… Commented Mar 8, 2021 at 2:10
  • thank you, but unfortunately it does not Commented Mar 8, 2021 at 2:20
  • @RichardMcCormick it does, go read it again. You don't have an action path set, and it's trying to POST to the page it came from. Commented Mar 8, 2021 at 2:23
  • Where do I set the action path to? I have tried using the folder which contains both files but this is not working either. Commented Mar 8, 2021 at 2:29
  • 1
    I think this may work for you <form action="{{ url_for('gfg') }}" method="post"> Commented Mar 8, 2021 at 3:17

1 Answer 1

2

Try the following:

@app.route('/', methods =["GET", "POST"])
def gfg():
    if request.method == "POST":
       # getting input with name = fname in HTML form
       if "fname" in request.form:
           first_name = request.form['fname]
       # getting input with name = lname in HTML form
       if "lname" in request.form:
           last_name = request.form["lname"]
    
       if first_name and last_name:
           print("Your name is "+first_name + last_name)
           
    return render_template("form.html")
Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer help you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.