欢迎访问宙启技术站
智能推送

Python中使用Bootstrap创建一个漂亮的表单页面

发布时间:2023-12-24 10:13:40

在Python中使用Bootstrap创建一个漂亮的表单页面非常简单和方便。Bootstrap是一个广泛使用的HTML、CSS和JavaScript框架,可以轻松地创建响应式和现代化的网页。

首先,确保已经安装了Python和Flask框架。可以使用pip install Flask命令来安装Flask框架。

接下来,创建一个Python脚本并导入必要的模块和类:

from flask import Flask, render_template, request

然后,创建一个Flask应用实例:

app = Flask(__name__)

接着,创建一个路由来处理表单页面的GET和POST请求:

@app.route('/form', methods=['GET', 'POST'])
def form():
    if request.method == 'POST':
        # 处理表单提交数据的逻辑
        name = request.form['name']
        email = request.form['email']
        message = request.form['message']
        return render_template('form.html', message=message)
    else:
        return render_template('form.html')

上述代码中的form函数处理了表单页面的GET和POST请求。当请求方法为POST时,从表单中获取数据,并返回一个包含消息的模板。当请求方法为GET时,只返回一个渲染了表单的模板。

最后,创建一个HTML模板来渲染表单页面。可以使用Bootstrap提供的CSS和组件来美化表单。

<!DOCTYPE html>
<html>
<head>
    <title>表单页面</title>
    <!-- 引入Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>表单页面</h1>
        <form method="POST">
            <div class="form-group">
                <label for="name">姓名:</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <div class="form-group">
                <label for="email">邮箱:</label>
                <input type="email" class="form-control" id="email" name="email">
            </div>
            <div class="form-group">
                <label for="message">消息:</label>
                <textarea class="form-control" id="message" name="message"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">提交</button>
        </form>
        {% if message %}
        <div class="alert alert-success" role="alert">
            {{ message }}
        </div>
        {% endif %}
    </div>
</body>
</html>

上述代码中的HTML模板使用了Bootstrap提供的表单组件和样式,包括form、form-group、form-control和btn等类。在表单提交后,如果有消息存在,则显示一个带有成功样式的消息框。

最后,通过运行应用实例的run方法来启动应用:

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

运行脚本后,访问http://localhost:5000/form即可看到一个具有表单的漂亮页面。可以填写表单并提交,之后会显示一个成功消息。

这就是使用Python和Bootstrap创建一个漂亮的表单页面的简单示例。根据具体需求,可以使用更多的Bootstrap组件和样式来定制表单页面的外观和功能。