我尝试制作简单的应用程序,要求用户填写信息,然后在html页面中显示

时间:2014-12-07 00:32:45

标签: flask sqlalchemy flask-sqlalchemy

以下是app.py文件

from flask import Flask, render_template, url_for

from flask.ext.sqlalchemy import SQLAlchemy

#create application object
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'

#create the sqlalchemy object0
db = SQLAlchemy(app)

#import db schema
from models import *

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

@app.route('/pro', methods=['GET', 'POST'])
def new():
    if request.method == 'POST':
        if not request.form['username'] or not request.form['age'] or not request.form['Email']:
            flash('Please enter all the fields', 'error')

        #Check if the email address is valid. If not, raise an error
        elif not is_email_address_valid(request.form['email']):
            flash('Please enter a valid email address', 'error')

        else:
            # The data is valid. So create a new 'tabel' object
            # to save to the database
            tabel = BlogPost(request.form['name'],
                             request.form['age'],
                             request.form['Email'])

            #Add it to the SQLAlchemy session and commit it to
            #save it to the database
            db.session.add(tabel)
            db.session.commit()

            #Flash a success message
            flash('Comment was successfully submitted')

        return redirect(url_for('profile.html'))

  #start the server with the run() method
  if __name__ == '__main__':
  app.run(debug=True)

models.py

#import data base name db
from app import db

# define the tabel name
__ tablename__ = "BlogPost"

class BlogPost(db.Model):    
    id = db.Column(db.Integer, primary_key=True)
    username= db.Column(db.String, nullable=False)
    age= db.Column(db.Integer, nullable=False)
    Email = db.Column(db.String, nullable=False)

    def __init__(self, username, age, Email):
        self.username = username
        self.age = age
        self.Email= Email

    def __repr__(self):
        return '<username{}'.format(self.username) 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <link>
  <href="/bootstrap.min.css" rel="stylesheet">    
</head>
<body>
  <div class="container">
     <div class="header">
       <h3 class="text-muted">Please fill the information</h3>
     </div>
     </hr>

     {%- for category, message in get_flashed_messages(with_categories=true) %}
       <div class="alert alert-danger">
       {{ message }}
        </div>
      {%- endfor %}

      <form class="form-horizontal" action="{{ request.path }}" method="post">
        <div class="form-group">
          <label for="name" class="col-lg-2 control-label">Name</label>
          <div class="col-lg-2">
            <input type="text" class="form-control" name="name" placeholder="Name">
          </div>
        </div>
        <div class="form-group">
          <label for="email" class="col-lg-2 control-label">Email</label>
          <div class="col-lg-2">
            <input type="text" class="form-control" name="email" placeholder="Email">
          </div>
        </div>
        <div class="form-group">
          <label for="comment" class="col-lg-2 control-label">age</label>
          <div class="col-lg-2">
            <input type="text" class="form-control" name="age" placeholder="age">
          </div>
        </div>
        </div>
        <div class="form-group">
          <div class="col-lg-offset-2 col-lg-2">
            <input type="submit" class="btn btn-primary" value="Submit">
          </div>
        </div>
      </form>
    </div>
  </body>
</html>

profile.html

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Profile</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="static/bootstrap.min.css" rel="stylesheet" media="screen">
  </head>
  <body>
    <div class="container">
        <h1>Welcome to profile!</h1>
        <br>
        <p>Click <a href="/logout">here</a> to logout.</p>
        <br><br>
        <h3>Posts:</h3>
        {% for tabel in BlogPost %}
        <strong>Name:</strong> {{ tabel.username }} <br>
        <strong>age:</strong> {{ tabel.age}} <br>
        <strong>Email:</strong> {{ tabel.Email}} <br>
        <br>
        {% endfor %}
        {% for message in get_flashed_messages() %}
        {{ message }}
        {% endfor %}
       </div>
  </body>
</html>

index.html当我按下提交但未通过验证且未指向profile.html时出现错误

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

我做错了什么,如何解决?

1 个答案:

答案 0 :(得分:1)

您正在将表单提交给不接受POST请求的index端点。我认为您真正要做的是将表单提交到new端点。为此,请更改

<form class="form-horizontal" action="{{ request.path }}" method="post">

<form class="form-horizontal" action="{{ url_for('new') }}" method="post">