问题
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
form.jobs[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'])
@login_required
def edit_job():
"""
edit job
"""
company_list = Company.Company_list()
form_title = "Edit job Form"
if request.method != 'POST':
form = JobForm()
form.jobs[0].company.choices = company_list
return render('form.html', form=form, form_title=form_title)
form = JobForm(request.form)
if form.add_job.data:
new_item_job = form.jobs.append_entry()
new_item_job.company.choices = company_list
return render('form.html', form=form, form_title=form_title)
form.validate
if form.errors != dict():
return render('form.html', form=form, form_title=form_title)
# save data
flash(_("Edit successfully!"))
return render('registration/succesful.html')
回答1:
There is a better way to do this:
form.jobs[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
来源:https://stackoverflow.com/questions/11368067/how-to-append-a-new-wtforms-formfield-with-initial-data-as-default