Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-generate full HTML from a WTForms form

I'm trying to create a simple WTForms-based admin interface for an SQLAlchemy app, using Jinja2 templates.

I've read the docs of WTForms-Alchemy and I understand that it can auto-generate a form from my model just via a few lines of code, like:

class UserForm(ModelForm):
    class Meta:
        model = User

My problem is that even though I have this form auto-generated, I found no resource anywhere about how can I make it into a functional HTML page. There are a few snippets about rendering errors for fields, as well as some SO answers mentioning macros for rendering whole fields, but I found absolutely no resource about how to generate a full, functional form automatically.

// I understand that this is something what Flask-Admin might do already, I'm not using Flask so this is not a possibility unfortunately.

like image 442
hyperknot Avatar asked Dec 01 '15 03:12

hyperknot


1 Answers

WTForms leaves it up to you to figure out how to you want to render out your form after you pass it into your template. The simplest way to render a form would be to just iterate through your form and render the fields. When a field (or its label) is called, it emits HTML.

<form action="/some_url" method="POST">
   {% for field in form %}
       {{ field.label() }}
       {{ field() }}
   {% endfor %}

   <button type="submit" />
</form>

The macros provided here provide an automated way to generate HTML surrounding these fields.

like image 195
jumbopap Avatar answered Oct 24 '22 06:10

jumbopap