Flask-具有动态标签的切换按钮

时间:2018-06-27 08:22:34

标签: python flask jinja2 flask-wtforms

我是Flask的新手,并且想在我的网站上创建一个On / Off切换按钮。我想知道是否以及如何可以包括动态标签。下图显示了我的想法:

我当时正在考虑使用wtfforms SubmitField,但我不太了解如何在route.py文件和html模板之间实现这种动态行为。我在想这样的事情:

forms.py:

from flask_wtf import FlaskForm
from wtforms import SubmitField

class PowerSwitchForm(FlaskForm):
    power_switch = SubmitField("ON")

routes.py:

from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import PowerSwitchForm

@app.route('/power', methods=['GET', 'POST'])
def power():
  power_switch = PowerSwitchForm()
  if power_switch.power_switch.label.text == "ON" and power_switch.validate():
    flash("Power has been turned ON")
    power_switch.power_switch.label.text = "OFF"
    return redirect(url_for('power')
  elif power_switch.power_switch.label.text == "OFF" and power_switch.validate():
    flash("Power has been turned OFF")
    power_switch.power_switch.label.text = "ON"
    return redirect(url_for('power')
  return render_template('power.html', form0=power_switch)

power.html:

<!DOCTYPE html>

{% extends "base.html" %}

{% block content %}
<h2>Power switch</h2>
<form action="" method="post" novalidate>
  {{ form0.hidden_tag() }}
  {{ form0.power_switch() }}
</form>    
{% endblock %}

2 个答案:

答案 0 :(得分:1)

单击切换按钮时,可以使用jquery处理所需的操作。另外,如果在切换按钮时有后端处理需要执行,则可以使用ajax。这个答案说明了两者。 bootstrap-toggle是一个库,可轻松实现切换。要使用,请复制以下header标签值:

显示“已切换”或“未切换”的简单切换:

<html>
  <body>
    <head>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
      <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
      <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    </head>
    <input type="checkbox" class='toggle' checked data-toggle="toggle">
    <div class='status'>Toggled</div>
  </body>
  <script>
  $(document).ready(function() {
   $('.toggle').click(function() {
      var current_status = $('.status').text();
      if (current_status === 'Untoggled'){
         $('.status').html('Toggled');
      }
      else{
        $('.status').html('Untoggled');
      }

    });
   });
 </script>
</html>

enter image description here

触发“切换”或“取消切换”的后端脚本的切换:

在模板中,稍微更改script

<script>
 $(document).ready(function() {
  $('.toggle').click(function() {
   var current_status = $('.status').text();
   $.ajax({
    url: "/get_toggled_status",
    type: "get",
     data: {status: current_status},
     success: function(response) {
      $(".status").html(response);
     },
     error: function(xhr) {
      //Do Something to handle error
     }
   });
  });
});
</script>

然后,在您的应用中,创建一条路线/get_toggled_status

@app.route('/get_toggled_status') 
def toggled_status():
  current_status = flask.request.args.get('status')
  return 'Toggled' if current_status == 'Untoggled' else 'Untoggled'

该示例与纯html / jquery解决方案具有相同的作用,但是,它确实演示了使用切换开关时如何与后端进行通信。

答案 1 :(得分:1)

我也是 Flask 的新手。这是我尝试过的带有烧瓶的纯 python 代码。 看起来很有效。

在模板/演示.html :

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
<div class="page-header">
    {{ wtf.quick_form(form) }}
</div>
{% endblock %}

在 demo.py 中:

from flask              import Flask, render_template, redirect, url_for                          
from flask_bootstrap    import Bootstrap
from flask_wtf          import FlaskForm
from wtforms            import SubmitField

class PowerState(FlaskForm) :
    state = SubmitField('OFF')

app = Flask(__name__)
Bootstrap(app)

app.config['SECRET_KEY'] = 'YOUR SECRET KEY'

@app.route('/', methods=['GET', 'POST'])
def home() :
    form = PowerState()

    if form.validate_on_submit() :
        if form.state.label.text == 'OFF' :
            PowerState.state = SubmitField('ON')
        elif form.state.label.text == 'ON' :
            PowerState.state = SubmitField('OFF')

        return redirect(url_for('home'))
    return render_template('demo.html', form=form)

然后运行: 烧瓶运行

问候,Alex.Wu