Python Flask: Sending a form class argument from another function to prepopulate default
<p>I need to prepopulate form fields with database (dataset) values.
The problem is that I don't know how to send the argument to the form class.</p>

<p><strong>forms.py</strong></p>

<pre><code># coding: utf-8
from db import produtosalca as produtos ##dataset imports db['table']
from flask_wtf import FlaskForm
from wtforms import TextField, BooleanField, SubmitField, TextAreaField, validators, ValidationError

class ProductForm(FlaskForm,produto):
    descricao = TextField("Nome", default=produto.Descricao)        
    classificacaoFiscal = TextField("NCM", default=produto.ClassificacaoFiscal) 
    mva = TextField("MVA",default=produto.MVA)
</code></pre>

<p>app.py</p>

<pre><code># coding: utf-8
import os
from werkzeug import secure_filename
from flask import (
    Flask, request, send_from_directory, render_template, current_app, flash
    )
from db import produtosalca
from forms import ContactForm, ProductForm

app = Flask("alcax")

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
app.config['MEDIA_ROOT'] = os.path.join(PROJECT_ROOT, 'media_files')

app.secret_key = 'development key'

@app.route('/productform', methods=['GET','POST'])
def productform(product):
    form = ProductForm(request.form,product) ## here i was gonna send product
    if request.method == 'POST':
        'posted'
    elif request.method == 'GET':
        return render_template('productform.html', form=form.content())
</code></pre>

<p>Well everything I tried always get me the error </p>

<pre><code>'produto' is not defined
</code></pre>

<p>I'm a beginner in py. Have been researching all night long. Thanks in advance.</p>

<p>Note that <code>class ProductForm(FlaskForm)</code> means ProductForm inherets from FlaskForm. A simple solution for your case would be as follows:</p>

<p><strong>forms.py:</strong></p>

<pre><code>from flask_wtf import FlaskForm
from wtforms import TextField


class ProductForm(FlaskForm):
    descricao = TextField("Nome")
    classificacaoFiscal = TextField("NCM")
    mva = TextField("MVA")
</code></pre>

<p><strong>app.py:</strong></p>

<pre><code>from flask import Flask, render_template, redirect, request
from forms import ProductForm

app = Flask(__name__)
app.secret_key = 'development key'


@app.route('/productform', methods=['GET','POST'])
def productform():
    form = ProductForm(descricao='default_descricao', classificacaoFiscal='default_classificacaoFiscal', mva='default_mva')
    if form.validate_on_submit():
        form = ProductForm(request.form)
        # Do something with your form and redirect the user to some page.
    return render_template('productform.html', form=form)


if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)
</code></pre>

<p><strong>templates/_formhelpers.html</strong></p>

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

<p><strong>templates/productform.html</strong></p>

<pre><code>&lt;html !DOCTYPE&gt;
&lt;head&gt;
&lt;title&gt;Flask WTF&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
{% from "_formhelpers.html" import render_field %}
&lt;form method="POST" action="/submit"&gt;
    &lt;dl&gt;
    {{ form.hidden_tag() }}
    {{ render_field(form.descricao, size=20) }}
    {{ render_field(form.classificacaoFiscal, size=20) }}
    {{ render_field(form.mva, size=20) }}
    &lt;/dl&gt;
    &lt;input type="submit" value="Go"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>Edit to take into account the new queries in the comments below:</strong></p>

<p><strong><em>forms.py:</em></strong></p>

<pre><code>class ProductForm(FlaskForm):

    descricao = TextField("Nome")
    classificacaoFiscal = TextField("NCM")
    mva = TextField("MVA")
    # ...

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        if 'product' in kwargs:
            self.descricao.data = kwargs['product'][0]
            self.classificacaoFiscal.data = kwargs['product'][1]
            self.mva.data = kwargs['product'][2]
            # ...
</code></pre>

<p><strong><em>app.py:</em></strong></p>

<pre><code>@app.route('/productform', methods=['GET','POST'])
def productform():
    # product to be retrieved from your database
    form = ProductForm(product=product)
    if form.validate_on_submit():
        form = ProductForm(request.form)
        # Do something with your form and redirect the user to some page.
    return render_template('productform.html', form=form)
</code></pre>

python forms flask arguments flask-wtforms