3

Recently, I created a Python project that uses Flask. In Flask, the forms and views are defined in two .py files and then they are used in the templates HTML.

Here is my forms.py

from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    submit = SubmitField('Submit')

Here are my views (views.py)

from flask import render_template, session, redirect, url_for,     current_app
from .. import db, smk
from ..models import User
from ..email import send_email
from . import main
from .forms import NameForm

@main.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            session['known'] = False
            if current_app.config['FLASKY_ADMIN']:
                send_email(current_app.config['FLASKY_ADMIN'], 'New User','mail/new_user', user=user)
        else:
            session['known'] = True
        session['name'] = form.name.data
        return redirect(url_for('.index'))
    return render_template('index.html',form=form, name=session.get('name'),known=session.get('known', False))

Here is my template (index.html)

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

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
    {% if not known %}
    <p>Pleased to meet you!</p>
    {% else %}
    <p>Happy to see you again!</p>
    {% endif %}
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

And now I need create a table list form, it queried from MySQL database, and I also need a checkbox like:

selectall| id   | name    | value     
------------------------------------
checkbox | 1     | name1  | test1
------------------------------------
checkbox | 2     | name2  | test2
------------------------------------
checkbox | 3     | name3  | test3

submitbutton

I hope it works when I click "select all", all items are selected or canceled, and when I click certain item's checkbox the item is selected. Then clicking the submit button, the selected item will as the condition to update database item relationed.

Additionally, the query content is not fixed. Some tables contain 4 columns and some tables contain 7 or other number columns. I must create the table list dynamically.

In flask forms.py I do not now how to create the table list first and how it called by .html, then how can I dynamically create then? And how does the checkbox work in table list form?

Makyen
  • 31,849
  • 12
  • 86
  • 121
kaku21
  • 129
  • 1
  • 1
  • 11

0 Answers0