user11876616
user11876616

Reputation:

Flask question: redirect not behaving as expected

I'm working on my first flask practice project and can't figure out why redirect does not work. The posts page has blog posts, and the edit page at /post/edit/id is supposed to update them. The form seems to work but when you save it goes to /posts/edit/posts/edit/1 rather than just /posts, even though /posts is passed in redirect. Here's the main code:

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime


app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
db = SQLAlchemy(app)

class Blogpost(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.String(25), nullable=False, default='N/A')
    title = db.Column(db.String(30), nullable=False)
    content = db.Column(db.String(150), nullable=False)
    date_posted = db.Column(db.DateTime, default=datetime.utcnow)


def __repr__(self):
    return str(self.id)


@app.route('/home')
@app.route('/')
@app.route('/posts', methods=['GET', 'POST'])
def hello():
    if request.method =='POST':
        post_title = request.form['title']
        post_author = request.form['author']
        post_content = request.form['content']
        new_post = Blogpost(title=post_title, author=post_author, content=post_content)
        db.session.add(new_post)
        db.session.commit()
        return redirect('/posts')
    else:    
        all_posts = Blogpost.query.order_by(Blogpost.date_posted).all()
        return render_template('posts.html', posts=all_posts)

@app.route('/posts/delete/<int:id>')
def delete(id):
    post = Blogpost.query.get_or_404(id)
    db.session.delete(post)
    db.session.commit()
    return redirect('/posts')

@app.route('/posts/edit/<int:id>', methods=['GET', 'POST'])
def edit(id):

    post = Blogpost.query.get_or_404(id)
    if request.method == 'POST':
        post.title = request.form['title']
        post.author = request.form['author']
        post.content = request.form['content']
        db.session.commit()
        return redirect('/posts')
    else:    
        return render_template('edit.html', post=post)   


@app.route('/about')
def about():
    return render_template('aboutus.html', title='About')  


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

And here's the html:

{% extends 'base.html' %}


{% block content %}

<h1>Edit Post</h1>
<hr>

<form action='posts/edit/{{ post.id }}' method='POST'>
    Title: <input type='text' name='title' id='title', value={{post.title}}>  
    <hr>
    Author: <input type='text' name='author' id='author', value={{post.author}}>
    <hr>
    Post: <input type='text' name='content' id='content', value= {{post.content}} >
    <hr>
    <input type='submit' value='Save'>
</form>

{% endblock %}

The base html file is this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% if title %}
        <title>{{ title }}</title>
    {% else %}
        <title>Welcome</title>
    {% endif %}    
</head>
    {% block content %}
    {% endblock %}
<body>
    {% block content2 %} 
    {% endblock %}   

</body>
</html>

Upvotes: 0

Views: 44

Answers (1)

Mert Bilgi&#231;
Mert Bilgi&#231;

Reputation: 178

redirect example:

from flask import url_for

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

@app.route('/sample')
def Sample():
    return redirect(url_for('Index'))

When the user enters the "/ sample" path, it is directed to the / index path

Upvotes: 1

Related Questions