Flask-Wtf

May 29, 2015

Нашел у себя вот такой код, он немного попахивает.

@auth.route('/cabinet', methods=["POST", "GET"])
@login_required
def cabinet():
    u = current_user
    form = None
    form = CabinetForm()
    if form.validate_on_submit():
        u.phone = form.phone.data
        u.notifysms = form.notifysms.data
        u.notifyemail = form.notifyemail.data
        u.about = form.about.data
        u.name = form.name.data
        u.company = form.company.data
        u.city = form.city.data
        u.address = form.address.data
        db.session.add(u)
        db.session.commit()
        return redirect(url_for('auth.cabinet'))
    form.phone.data = u.phone
    form.notifysms.data = u.notifysms
    form.notifyemail.data = u.notifyemail
    form.name.data = u.name
    return render_template('auth/cabinet.html', user=u, form=form)
$ virtualenv venv
$ source venv/bin/action
$ pip install Flask-Bootstrap Flask Flask-Wtf

В итоге получилось вот такое более приятный пример:

# -*- coding: utf-8 -*-
from flask import Flask, render_template_string
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField, IntegerField, BooleanField


app = Flask(__name__)
app.secret_key = 'asdada'
boostrap = Bootstrap()
boostrap.init_app(app)


class QueryForm(Form):
    age = IntegerField()
    name = StringField()
    login = StringField()
    offert = BooleanField(default=False)
    submit = SubmitField()

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

{% block title %}index{% endblock %}
{% block content %}
    <div class="container">
      {{user}}
      {{wtf.quick_form(form)}}
    </div>
{% endblock %}
'''


@app.route('/', methods=["POST", "GET"])
def index():
    form = QueryForm()
    user = {'age': 18, 'name': 'vlad', 'login': 'loki', 'offert': True}
    if form.validate_on_submit():
        for i in form._fields:
            if i != 'csrf_token' and i != 'submit':
                user[i] = form[i].data
        return render_template_string(tpl, form=form, user=user)
    for i in form._fields:
        if i not in ['csrf_token', 'submit']:
            form[i].data = user[i]
    return render_template_string(tpl, form=form, user=user)


app.run(port=8080, debug=True)

Итог

@auth.route('/cabinet', methods=["POST", "GET"])
@login_required
def cabinet():
    form = CabinetForm()
    if form.validate_on_submit():
        for i in form._fields:
            if i not in ['csrf_token', 'submit']:
                current_user[i] = form[i].data
        db.session.add(current_user)
        db.session.commit()
    for i in form._fields:
        if i not in ['csrf_token', 'submit']:
            form[i].data = current_user[i]
    return render_template('auth/cabinet.html', form=form)