Flask.redirect(url_for()) not redirecting

Question:

So I know that there are many already similar question and I’ve browsed about 5 now.
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:

enter image description here

But nothing is moving and I stay in the "http://localhost:3000/create-artist" URL for some reason.

Here’s my python (note that for test and learning purposes, I’m not sending anything to the db yet):

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:

/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 %}
Asked By: Martin Carre

||

Answers:

You can’t redirect page through flask(back end) if posting form through JS(front end). 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.

Answered By: Ajay K
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.