Home > other >  HTML button to next page is not working in Flask development server
HTML button to next page is not working in Flask development server

Time:10-08

I have two pages index.html having code as following

    <form action="/" method="POST">
        <div class="form-group">
            <textarea class="form-control"  name="text" placeholder="Enter Text" rows="6"></textarea>
            
          </div>
    <input type="submit" class="btn btn-primary">

    </form>


    <button>
</div>
<div class="col-md-3  col-sm-1"></div>
<input type=button onClick="location.href='upload.html'"
 value='click here'>
</div>
<button>

It has js and css in head. As you can see there is a button to go to upload.html page, which contains code to upload file as following

  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file" accept=".pdf"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
  </body>

If I open index.html page in a browser and click on click here button it redirects me to the intended page, But when I run Flask app and try to click on this button it gives 404 error. Right now I haven't created any Flask method for this file. I have tried to add absolute path to upload.html file and ./upload.html and almost every method to create a button mentioned here. I also tried to redirect it to a blank page and index.html itself but every time the error is same. It is only giving me error with local HTML files if I give an address of some website it redirects me to it. Can someone help me with what I need to do to make it work?

CodePudding user response:

I think you need to create a route and point the input element to the new page. Right now that won't work within Flask because the app does not "see" the upload.html page.

so you would first create a route in your routes.py or app.py

@app.route(methods=["GET", "POST"])
def file_upload():
    return render_template("upload.html")

and then in your index.html you would point the input to this route:

<input type=button href="{{url_for('file_upload')}}" value='click here'>

just remember, url_for as a function points to the function name, not the html template itself. So here you call url_for which in turn calls file_upload which in turn renders upload.html.

  • Related