从Jinja2下拉菜单将变量传递给Python

时间:2014-03-26 17:59:34

标签: google-app-engine python-2.7 drop-down-menu jinja2 webapp2

我是一名编程新手。如何将带有Jinja2模板的下拉菜单中的变量传递到我的Python 2.7代码中?我在Google App Engine上使用了webapp2框架。

我的代码目前看起来像这样:

class AccountNew(Handler):
    def get(self):
        activities = ['Select one', 'Camping', 'Hiking', 'Fishing']
        self.render('account-new.html', activities = activities)

    def post(self):
        acct_name = self.request.get('acct_name')
        activity = self.request.get('activity')
        self.write(acct_name)
        self.write(activity)

我的Jinja2模板名为" account-new.html"看起来像这样:

<form method="post">

  <label>
    <div>Account Name</div>
    <input type="text" name="acct_name" value="{{ acct_name }}">
  </label>

  <label>
    <div>Parent</div>
    <select>
      {% for activity in activities %}
          <option value="{{ activity }}">{{ activity }}</option>
      {% endfor %}
    </select>
  </label>

  <input type="submit">

</form>

acct_name 字符串会被传回,但活动字符串似乎会以空字符串形式返回。任何见解将不胜感激。

1 个答案:

答案 0 :(得分:10)

你已经离开了这个名字&#39; select元素的属性。应该是这样的:

<select name="activity">
  {% for activity in activities %}
      <option value="{{ activity }}">{{ activity }}</option>
  {% endfor %}
</select>