“ Flask Sqlite数据库未显示查询”

时间:2019-03-28 03:08:23

标签: python-3.x flask-sqlalchemy

我正在编写一个Web应用程序,该应用程序是小狗的收养站点,其中具有添加puupy,收养后删除之类的功能。 但这不显示/不显示添加到数据库中的幼犬。 我是初学者,所以我什至不确定是否在数据库中添加了数据。请帮忙!

我试图清除init方法,但似乎不起作用

from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
import os
from flask_migrate import Migrate
from forms import AddForm,DelForm
basedir = (os.path.abspath(os.path.dirname(__file__)))
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///dbdir/test.db'

app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
app.config['SECRET_KEY'] = 'Random'
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"Dog Name ={self.name}"


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

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

@app.route("/delete", methods=['GET', 'POST'])
def del_pup():
    form = DelForm()
    if form.validate_on_submit():
        id = form.id.data
        pup = Puppy.query.get(id)
        db.session.delete(pup)
        db.session.commit()
    return render_template('delete.html', form=form)

@app.route('/display')
def display():
    puppies = Puppy.query.all()
    return render_template('display.html', puppies=puppies)


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

###################################### **Forms.py**#######################

from flask_wtf import FlaskForm
from wtforms import *

class AddForm(FlaskForm):
    name = StringField("What is the dog name")
    submit = SubmitField('Submit')

class DelForm(FlaskForm):
    id = StringField("Id to Delete?")
    submit = SubmitField("Really want to delete")

Add.html

{% extends "base.html" %}
    {% block content %}



    <form>
        {# This hidden_tag is a CSRF security feature. #}
        {{ form.hidden_tag() }}
        {{form.name.label}} {{form.name}}
        {{form.submit()}}
    {% endblock %}

display.html

{% extends "base.html" %}
{% block content %}
    <h1>Here is a list of all available puppies.</h1>
  <ul>
    {% for pup in puppies  %}
    <li>{{pup}}</li>
    {% endfor %}
  </ul>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

您的应用看起来不错,但是您应该取消对__init__类的Puppy方法的注释。 您是否忘记了运行迁移? 尝试在控制台中运行它:

flask db init
flask db migrate
flask db upgrade