Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable into Python from Jinja2 Drop-down menu

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.

like image 649
bholben Avatar asked Mar 26 '14 17:03

bholben


1 Answers

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>
like image 127
Gwyn Howell Avatar answered Nov 15 '22 08:11

Gwyn Howell