Method not allowed error 405/ URL not found in Flask, when submitting a form

61 Views Asked by At

I am using Flask for running a website and every time I try to submit the form and write it to a csv file I get the "method not allowed error".

This is the HTML portion of the code:

<footer id="footer">
   <section>
      <form method="post" action="/generic">
         <div class="fields">
            <div class="field">
               <label for="name">Name/Organization</label>
               <input type="text" name="name" id="name" />
            </div>
            <div class="field">
               <label for="email">Email</label>
               <input type="text" name="email" id="email" />
            </div>
            <div class="field">
               <label for="message">message</label>
               <input type="text" name="message" id="message" />
            </div>
         </div>
         <ul class="actions">
            <li><input type="submit" value="Send Message" /></li>
         </ul>
      </form>

and this is the part of the Flask Python server:

import csv

from flask import Flask, render_template, request, send_from_directory, redirect
import os
import csv

app = Flask(__name__)


@app.route('/')
def my_home():
    return render_template('index.html')



@app.route('/<string:page_name>')
def html_page(page_name):
    return render_template(page_name)



def write_to_csv(data):
    with open('database.csv', mode='a',newline='') as database2:
        name = data['name']
        email = data['email']
        message = data['message']
        csv_writer = csv.writer(database2, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        csv_writer.writerow([name,email,message])
@app.route('/generic', methods=['GET', 'POST'])
def submit_form():
    print("You have reached the right place")
    if request.method == 'POST':
        try:
            data = request.form.to_dict()
            write_to_csv(data)
        except Exception as e:
            print(e)
            return 'Something went wrong, It did not save in the data base'
    return redirect('generic.html')

This is all occurring in the index.html file until the form is submitted and is supposed to be redirected to the generic.html file. But I get not found the URL: (http://127.0.0.1:5000/generic)

I'm a self-taught Python programmer and I've been wondering around creating the website but I have been stuck for a while here, I am not familiar with HTML so I tried changing the action to submit form as well as the @app.route("submit_form") with no luck. Thank you for any help in advance :)

Furthermore, if I try to add changes directly to the HTML on the action attribute, the server gets interrupted and doesn't load the index.html file.

1

There are 1 best solutions below

3
Kate On

It looks like you want to show the same page again, after posting the form data. Then there is no need for redirect. Something like this should do. render_template will be run after processing optional POST data. Proper indentation is of course critical.

@app.route('/generic', methods=['GET', 'POST'])
def submit_form():
    print("You have reached the right place")
    if request.method == 'POST':
        try:
            data = request.form.to_dict()
            write_to_csv(data)

        except Exception as e:
            print(e)
            return 'Something went wrong, It did not save in the data base'

    return render_template('generic.html')

It would be more user-friendly to add a conditional message in your page.

Also, instead of hardcoding the URL in your Jinja template you could do this:

<form method="post" action="{{ url_for('submit_form') }}">

Then, Jinja will generate the URL based on the route definition for that submit_form function. One benefit is that if you rename your routes in the Python code, the templates will continue to work, as long as the matching function is not renamed.