Flask Form Rendering + wtform

code:

from flask import Blueprint, render_template, abort from flask.ext.wtf import Form import os from jinja2 import TemplateNotFound from models import Member from wtforms.ext.sqlalchemy.orm import model_form @simple_page.route('/register') def register(): form = model_form(Member, Form) return render_template('register.html', form=form, name="bad") class Member(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) email = db.Column(db.String(50), nullable=False, unique=True) 

and, in my opinion:

  <p class="txt11 colorb"> {{ form.name }} </p> 

outputs <UnboundField(TextField, (), {u'default': None, u'filters': [], u'validators': [<wtforms.validators.Required object at 0x7f62f59b5590>, <wtforms.validators.Length object at 0x7f62f59b55d0>]})> , not the actual field. how to get real form / field using wtform?

+6
source share
3 answers

You pass the template the class is not a template into the template. The model_form method generates a new class dynamically, which can be reused, extended and used in a different way, like any other form subclass. It is also not necessary to generate this form class every time you run your view, so you can move this call outside of your view.

You pass an unconfirmed class, also why you get weird UnboundField behavior (how WTForms handles declarative field creation)

The fix is ​​simple:

 MemberForm = model_form(Member, base_class=Form) @simple_page.route('/register') def register(): form = MemberForm(name=u'bad') return render_template('register.html', form=form) 
+11
source

You need to do a little more work:

 {{ form.name.label }} : {{ form.name()|safe }} 

Or you can use a convenient snippet :

 {% macro render_field(field) %} <dt>{{ field.label }} <dd>{{ field(**kwargs)|safe }} {% if field.errors %} <ul class=errors> {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %} </dd> {% endmacro %} 

Of course, customize the HTML rendering. Save this file somewhere in your templates directory, and then in the main template. Here is its formhelpers.html :

 {% from "formhelpers.html" import render_field %} <form method=post action="/register"> <dl> {{ render_field(form.name) }} {{ render_field(form.email) }} </dl> <p><input type=submit value=Register> </form> 
+2
source

I know this is pretty old, but I had the same problem and I want to share my solution for futures needs.

I also got the html provided by "UnboundField". After struggling with the code, I found out that I was using:

 from wtforms import Form 

And it looks good, but when using Flask I had to do this:

 from flask.ext.wtf import Form 

The problem is fixed. Hope this helps

+1
source

Source: https://habr.com/ru/post/944390/


All Articles