[英]How do I generate dynamic fields in WTForms
我正在嘗試根據此文檔在 WTForms 中生成一個具有動態字段的表單http://wtforms.simplecodes.com/docs/1.0.2/specific_problems.html#dynamic-form-composition
我有這個子表單類,它允許用戶從列表中選擇要購買的項目:
class Item(Form):
itmid = SelectField('Item ID')
qty = IntegerField('Quantity')
class F(Form):
pass
將有多個類別的購物項目,因此我想根據用戶將選擇的類別生成一個動態選擇字段:
fld = FieldList(FormField(Item))
fld.append_entry()
但我收到以下錯誤:
AttributeError: 'UnboundField' object has no attribute 'append_entry'
我做錯了什么,還是沒有辦法在 WTForms 中做到這一點?
我今晚遇到了這個問題並最終解決了這個問題。 我希望這對未來的人有幫助。
class RecipeForm(Form):
category = SelectField('Category', choices=[], coerce=int)
...
@mod.route('/recipes/create', methods=['POST'])
def validateRecipe():
categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
form = RecipeForm(request.form)
form.category.choices = categories
...
@mod.route('/recipes/create', methods=['GET'])
def createRecipe():
categories = [(c.id, c.name) for c in g.user.categories.order_by(Category.name).all()]
form = RecipeForm(request.form)
form.category.choices = categories
return render_template('recipes/createRecipe.html', form=form)
我發現這篇文章也很有幫助
class BaseForm(Form):
@classmethod
def append_field(cls, name, field):
setattr(cls, name, field)
return cls
from forms import TestForm
form = TestForm.append_field("do_you_want_fries_with_that",BooleanField('fries'))(obj=db_populate_object)
我將擴展類BaseForm用於所有表單,並且在類上有一個方便的 append_field 函數。
返回帶有附加字段的類,因為(表單字段的)實例不能附加字段。
無需編寫完整代碼或測試代碼即可發布,但也許會給您一些想法。 此外,這可能只能幫助填充所需的數據。
您需要填寫SelectField
choices
才能看到數據並能夠選擇它。 你在哪里填的? 初始填寫應該在表單定義中,但如果你喜歡動態的,我建議你在創建這個表單的地方修改它以顯示給用戶。 就像你做一些form = YourForm()
然后將它傳遞給模板的視圖一樣。
如何用選項填寫表單的選擇字段? 你必須有元組列表,然后是這樣的:
form.category_select.choices = [(key, categories[key]) for key in categories]
form.category_select.choices.insert(0, ("", "Some default value..."))
此處的categories
必須是包含您的類別的字典,格式如{1:'One', 2:'Two',...}
因此,如果您在定義表單時將某些內容分配給選項,它將從一開始就擁有該數據,以及您需要在何處擁有用戶類別,只需在視圖中覆蓋它即可。
希望這會給你一些想法,你可以繼續前進:)
您是否嘗試過在表單實例上調用append_entry()
而不是 FieldList 定義?
class F(Form)
fld = FieldList(SelectField(Item))
form = F()
form.fld.append_entry()
這就是我讓它工作的方式。
class MyForm(FlaskForm):
mylist = SelectField('Select Field', choices=[])
@app.route("/test", methods=['GET', 'POST']
def testview():
form = MyForm()
form.mylist.choices = [(str(i), i) for i in range(9)]
奇怪的是,如果我使用coerce=int
這整個事情對我不起作用。 我自己是flask
初學者,所以我不確定為什么coerce=int
會導致問題。
WTForms 文檔:類 wtforms.fields.SelectField
選擇具有動態選擇值的字段:
class UserDetails(Form):
group_id = SelectField(u'Group', coerce=int)
def edit_user(request, id):
user = User.query.get(id)
form = UserDetails(request.POST, obj=user)
form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.