Pergunta

I'm a programming newbie. How do I pass a variable from a drop-down menu with Jinja2 templating into my Python 2.7 code? I'm using the webapp2 framework on Google App Engine.

My code currently looks like this:

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)

My Jinja2 template is named "account-new.html" and looks like this:

<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>

The acct_name string gets passed back, but the activity string seems to come back as an empty string. Any insights would be greatly appreciated.

Foi útil?

Solução

You have left the 'name' attribute off the select element. Should be like this:

<select name="activity">
  {% for activity in activities %}
      <option value="{{ activity }}">{{ activity }}</option>
  {% endfor %}
</select>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top