简体   繁体   中英

Python Flask redirect after form is submited not working

I'm developing small Flask app that will take some data to form and after it is done will print it. After form is submited it should redirect to different site (end point) but that is not happening. I used return redirect(url_for('<name>')) and return render_template('<name>.html') .

Inside form.html i use script to dynamically create new fileds if user needs it and submit actions is happening inside that script.

Code:

from flask import Flask, session, render_template, request, redirect, url_for
from os import urandom


app = Flask(__name__)

app.secret_key = urandom(24)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return render_template('login.html')


@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))


@app.route('/')
def index():
    login = False
    if 'username' in session:
        login = True
    return render_template('login_home.html', login=login)


@app.route('/form')
def form():
    if 'username' in session:
        return render_template('form.html')
    return redirect(url_for('index'))


@app.route("/getform", methods=["POST", "GET"])
def getform():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone = request.form.get('phone')
        address = request.form.get('address')
        names = request.form.getlist('name[]')
        emails = request.form.getlist('email[]')
        print(name, email, phone, address, names, emails)
        return redirect(url_for('index'))


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

and here is form.html file:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formular</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
 <script>

$(document).ready(function() {

var MaxInputs       = 10; //maximum input boxes allowed
var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton       = $("#AddMoreFileBox"); //Add button ID


var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added


$(AddButton).click(function (e)  //on add input button click
{
    if(x <= MaxInputs) //max input box allowed
    {
        FieldCount++; //text box added increment
        //add input box
        $(InputsWrapper).append('<div class="row"><p class="col-xs-6"><input type="text" placeholder="Unesite ime i prezime zaposlenika" class="form-control skill_list" name="name[]" id="field_'+ FieldCount +'"/><input type="email" placeholder="Unesite email zaposlenika" class="form-control skill_list" name="email[]" id="field_'+ FieldCount +'"/></p><a href="#" class="btn btn-danger removeclass">×</a></div>');
        x++; //text box increment
    }
    return false;
});

$("body").on("click",".removeclass", function(e){ //user click on remove text
    if( x > 1 ) {
        $(this).parent('div').remove(); //remove text box
         x--; //decrement textbox
    }
    return false;
})

 $('#submit').click(function(){
    $.ajax({
        url:"/getform",
        method:"POST",
        data:$('#add_skills').serialize()
    });
});

});
</script>
<style>
.row {padding:10px;}
</style>
<div class="container"><br/> <br/>
    <h2 align="center">Form</h2><div id="resultbox"></div>
    <div class="form-group">
        <form name="add_skills" id="add_skills">
        <div class="form-group">
            <input type="text" class="form-control" id="Name" aria-describedby="emailHelp"
                   placeholder="name" name="name" value="{{ name }}" required>
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="address" aria-describedby="emailHelp"
                   placeholder="address" name="address" value="{{ address }}" required>
          </div>
          <div class="form-group">
            <input type="text" class="form-control" id="phone" aria-describedby="emailHelp"
                   placeholder="phone" name="phone" value="{{ phone }}" required>
          </div>
          <div class="form-group">
            <input type="email" class="form-control" id="email" aria-describedby="emailHelp"
                   placeholder="email" name="email" value="{{ email }}" required>
          </div>
          <label>Additional info:</label>
        <div id="InputsWrapper">
            <div class="row">
                <div class="col-xs-6"><input type="text" name="name[]" placeholder="name" class="form-control name_list" />
                <input type="email" name="email[]" placeholder="email" class="form-control name_list" /></div>
                <div class="col-xs-6"><button type="button" name="add" id="AddMoreFileBox" class="btn btn-success">Add</button></div>
            </div>
        </div>
        <br/>
        <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
        </form>
    </div>
</div>
</body>
</html>

I will not post login.html and login_home.html because it is irelevant to this issue.

Problem is solved: problem was in form.html :

I removed:

$('#submit').click(function(){
    $.ajax({
        url:"/getform",
        method:"POST",
        data:$('#add_skills').serialize()
    });
});

added method="POST" and action="/form" to <form> tag:

<form name="add_skills" id="add_skills" action="/form" method="POST">

replaced:

<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />

with:

<button type="submit" class="btn btn-secondary">Submit</button>

in main.py added new endpoint with name form :

@app.route('/form', methods=["POST"])
def form():
    name = request.form.get("name")
    address = request.form.get("address")
    telephone = request.form.get("phone")
    email = request.form.get("email")
    print(name, address, telephone, email)
    return render_template("login_home.html")

So this solves my problem:)

I hope this will help someone with similar problem to mine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM