在Flask中的表单上显示同一页上的数据

2024-06-09 16:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些代码方面的帮助,我是flask&;我一直在尝试将数据显示在与表单相同的页面上,这意味着我不想重定向并将数据显示在不同的页面上,我做了一些尝试,但失败了,请帮助我

这是我的密码

import os
from forms import  AddForm
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
app = Flask(__name__)
# Key for Forms
app.config['SECRET_KEY'] = 'mysecretkey'

############################################

        # SQL DATABASE AND MODELS

##########################################
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
Migrate(app,db)

class Puppy(db.Model):

    __tablename__ = 'puppies'
    id = db.Column(db.Integer,primary_key = True)
    name = db.Column(db.Text)

    def __init__(self,name):
        self.name = name

    def __repr__(self):
        return f"Puppy name: {self.name}"

############################################

        # VIEWS WITH FORMS

##########################################
@app.route('/')
def index():
    form = AddForm()
    if form.validate_on_submit():
        name = form.name.data
        new_pup = Puppy(name)
        db.session.add(new_pup)
        db.session.commit()
        return redirect(url_for('index'))
    puppies = Puppy.query.all()
    return render_template('testing.html',form=form, puppies=puppies)

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

HTML代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Welcome</h1>

    <form method="post">
      {{form.hidden_tag()}}
      {{form.name.label}} {{form.name}}
      {{form.submit()}}

    </form>
    <ul>

    {% for pup in puppies %}
    <li>{{pup}}</li>
    {% endfor %}

        </ul>

  </body>
</html>

请帮我解决这个问题


Tags: namefromimportselfformconfigappflask
1条回答
网友
1楼 · 发布于 2024-06-09 16:12:16

如果您根本不想刷新页面,则需要使用ajax调用,否则就足够了:

@app.route('/', methods=['GET','POST'])
def index():
    form = AddForm()
    if form.validate_on_submit():
        name = form.name.data
        new_pup = Puppy(name)
        db.session.add(new_pup)
        db.session.commit()

    puppies = Puppy.query.all()
    return render_template('testing.html',form=form, puppies=puppies)

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

相关问题 更多 >