简体   繁体   English

Flask.redirect(url_for()) 不重定向

[英]Flask.redirect(url_for()) not redirecting

So I know that there are many already similar question and I've browsed about 5 now.所以我知道已经有很多类似的问题,我现在已经浏览了大约 5 个。 Problem is, though, I can't seem to find a similar problem to mine.但问题是,我似乎找不到与我的类似的问题。 Here's the deal:这是交易:

When posting my form, I get from the server:发布表单时,我从服务器获取:

> 127.0.0.1 - - [02/Dec/2022 10:37:53] "POST /create-artist HTTP/1.1" 302 -
> 127.0.0.1 - - [02/Dec/2022 10:37:53] "GET /artists-list HTTP/1.1" 200 -

back in the browser, the following response:返回浏览器,响应如下:

在此处输入图像描述

But nothing is moving and I stay in the "http://localhost:3000/create-artist" URL for some reason.但是没有任何动静,我出于某种原因留在“http://localhost:3000/create-artist”URL。

Here's my python ( note that for test and learning purposes, I'm not sending anything to the db yet ):这是我的 python(请注意,出于测试和学习目的,我还没有向数据库发送任何内容):

from flask import Flask, render_template, url_for, redirect, request, abort
from flask_sqlalchemy import SQLAlchemy
import os, sys

db = SQLAlchemy()
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = URI
db.init_app(app)


##########################################################
#################### CONTROLLERS #########################
##########################################################

# ---------------------------------------------
# ----------------- ARTISTS -------------------
# ---------------------------------------------

@app.route('/artists-list')
def artists_list():
    return render_template('artists.html', data='test')

@app.route('/create-artist', methods = ["GET", "POST"])
def create_artist():
    error = False
    if request.method == "POST":
        try: 
            artist = Artist(
                name = request.get_json()['name'],
                city = request.get_json()['city'],
                state = request.get_json()['state'],
                phone = request.get_json()['phone'],
                genres = request.get_json()['genres'],
            )
            # db.session.add(artist)
            # db.session.commit()
            print(artist)
        except:
            error = True
            # db.session.rollback()
            print(sys.exc_info())
        # finally: 
            # db.session.close()
        if not error:
            return redirect(url_for('artists_list'))
        else: 
            abort(500)


    return render_template('form/create-artist.html')


# --------------- END ARTISTS ------------------


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


##########################################################
###################### MODELS ############################
##########################################################


class Artist(db.Model): 
    __tablename__ = 'Artist'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    genres = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))

and the HTMLs:和 HTML:

/create-artist /创造艺术家

{% extends "artists.html" %}
{% block title %}New artist | Fy-yur{% endblock %}
{% block content %}
<div class="container">
    <h1>This is the create artist page!</h1>
    <form id="artist-form" class="col-md-4">

        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" placeholder="New Artist">
        </div>

        <div class="form-group">
            <label for="city">City</label>
            <input type="text" class="form-control" id="city" placeholder="Artist's City">
        </div>


        <div class="form-group">
            <label for="state">State</label>
            <select class="form-control" id="state">

            </select>
        </div>
        <div class="form-group">
            <label for="phone">Phone</label>
            <input type="text" class="form-control" id="phone" placeholder="Phone number">
        </div>

        <div class="form-group">
            <label for="genres">Genre</label>
            <select type="text" class="form-control" id="genres">

            </select>
        </div>
        <button type="submit" id="submit" class="btn btn-success">Create</button>
    </form>
</div>

<script>
    document.getElementById('artist-form').onsubmit = e => {
        e.preventDefault();
        const body = {};
        const formData = e.target;
        for (let i = 0; i < formData.length - 1; i++) {
            const currDataKey = formData[i].id;
            const currDataValue = formData[i].value
            body[currDataKey] = currDataValue;
        }
        fetch('/create-artist', {
            method: 'POST',
            body: JSON.stringify(body),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(res => console.log(res))
        .catch(e => console.log(e));
    }
</script>
{% endblock %}

/artists-list/ /艺术家列表/

{% extends "index.html" %}
{% block title %}Artists | Fy-yur{% endblock %}
{% block content %}
<h1>This is the artists page!</h1>
<div class="container">
    <a href={{ url_for('create_artist') }}>
        <button type="button" class="btn btn-success">
            New artist
        </button>
    </a>
</div>
{% endblock %}

You can't redirect page through flask(back end) if posting form through JS(front end).如果通过 JS(前端)发布表单,则不能通过 flask(后端)重定向页面。 You need to use JS redirection method for that because you are getting response in JS call where you can redirect based on response from back end.您需要为此使用 JS 重定向方法,因为您在 JS 调用中获得响应,您可以在其中根据来自后端的响应进行重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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