How to append a new wtforms FormField with initial data as default?


I have a form with wtform, I want to add a new form JobItemForm to my form JobForm using append_entry. JobItemForm has selectField named company. I add choice field data via model like this[0].company.choices = company_list

now I use append_entry without any choices and I recieve an error. So how can I call append_entry with some initial data?

class JobItemForm(Form):
    company = SelectField(_('company'), description=_('<a href="/education/institute/add/">new company"</a>'))
    title = TextField(_('title'), [validators.Length(min=4, max=250)])
    date_from = DateField(_("date_from"), format='%Y-%m-%d')
    date_to = DateField(_("date_to"), format='%Y-%m-%d')
    description = TextAreaField(_('description'))

class JobForm(Form):
    jobs = FieldList(FormField(JobItemForm), min_entries=3)
    add_job = SubmitField(_('Add job'))

some thing like this

@mod.route('/edit/', methods=['GET', 'POST'])
def edit_job():
    edit job
    company_list = Company.Company_list()
    form_title = "Edit job Form"
    if request.method != 'POST':
        form = JobForm()[0].company.choices = company_list
        return render('form.html', form=form, form_title=form_title)
    form = JobForm(request.form)
        new_item_job = = company_list
        return render('form.html', form=form, form_title=form_title)

    if form.errors != dict():
        return render('form.html', form=form, form_title=form_title)
    # save data
    flash(_("Edit successfully!"))
    return render('registration/succesful.html')
7/6/2012 8:22:19 PM

Accepted Answer

There is a better way to do this:[0].company.choices = company_list

Wtforms has extensions for GAE,Django and SQLAlchemy which supports orm backed form fields. Documentation of extensions.

For sqlalchemy, it works like this:

    from wtforms.ext.sqlalchemy.fields import QuerySelectField

    def fill_field():
         return Model.query

    myfield = QuerySelectField(query_factory=fill_field)

This snippet of code automatically fills the choices for you from the database model.

(I do not have you actual error so I am just guessing here)

The reason you are getting no choices error after add_job because you are filling choices only when it is a GET request. You need to add choices after a Post request too like this:

    def your_view():
        form = YourForm()
        form.fieldname.choices = choice_list
        # Here comes your code for GET and POST request both
7/7/2012 5:33:40 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow