Вопрос

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. When I load my /company/edit/2 url, the form doesn't populate the value.

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. 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". 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__). 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 = CompanyForm(**company)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top