简体   繁体   English

Flask-WTForms-简单的CRUD示例-值未填充表格

[英]Flask-WTForms - Simple CRUD Example - Value Not Populating Form

I've read every tutorial and bit of documentation I can find, but can't find my problem. 我已经阅读了所有可以找到的教程和一些文档,但是找不到我的问题。 I have made this as simple as possible, using "companies" as an example. 我以“ companies”为例,使这一过程尽可能简单。 When I load my /company/edit/2 url, the form doesn't populate the value. 当我加载/ company / edit / 2网址时,表单不会填充值。

view 视图

@app.route('/company/edit/<id>')
def company_edit(id):
  company = {'id': 2, 'company_name': 'SomeCo'} #dummy object
  form = CompanyForm(obj=company)
  #form = CompanyForm(None, company) #tried this too, based on API
  return render_template('company_form.html', form = form)

form object 形式对象

class CompanyForm(Form):
  company_name = TextField('company_name', validators = [Required()])

form template 表格模板

<!-- extend base layout -->
{% extends "base.html" %}

{% block content %}

<form action="" method="post" name="login">
    {{form.hidden_tag()}}
    <p>
        Company Name:<br>
        {{form.company_name(size=80)}}<br>
    </p>
    <p><input type="submit" value="Sign In"></p>
</form>

{% endblock %}

my understanding is that this should work - the route /company/edit/x would call company_edit(x), which declares the dummy company object (later to be pulled from a db), instantiates a form, passing the company object, then renders the template passing the form. 我的理解是,这应该行得通-路线/ company / edit / x会调用company_edit(x),它声明虚拟公司对象(后来从数据库中拉出),实例化表单,传递公司对象,然后呈现传递表单的模板。 The form template should be able to match the field names in the company object, to corresponding input names in the form object, and populate the text field with the value "SomeCo". 表单模板应该能够将公司对象中的字段名称与表单对象中的相应输入名称进行匹配,并使用值“ SomeCo”填充文本字段。 Am I missing something obvious? 我是否缺少明显的东西?

Thanks! 谢谢!

The obj keyword passed to a WTForms instance needs to have properties, not keys (in other words, it needs to respond to __getattr__ not __getitem__ ). 传递给WTForms实例的obj关键字需要具有属性,而不是键(换句话说,它需要响应__getattr__而不是__getitem__ )。 If you want to pass a dictionary-like object into your Form you need to use the splat operator ( ** ) to pass your dictionary in as keyword arguments: 如果要将类似字典的对象传递到Form ,则需要使用splat运算符( ** )将您的字典作为关键字参数传递:

form = CompanyForm(**company)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM