Reputation: 55
I look for answers but It was all about php. I got this index.html:
<form method="post">
<input type="checkbox" name="opts" value="opt1" opt[0]> option 1<br>
<input type="checkbox" name="opts" value="opt2" opt[1]> option 2<br>
<input type="checkbox" name="opts" value="opt3" opt[2]> option 3<br>
<br>
<input name="" type="submit" value="Save" >
</form>
and this main.py
import webapp2
import cgi
import os
import jinja2
from gaesessions import get_current_session
class MainHandler(webapp2.RequestHandler):
def get(self):
session=get_current_session()
opt=session.get('opt',[]) jinja_environment=jinja2.Environment(autoescape=True,loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
tpi_vars={"opt":opt}
template=jinja_environment.get_template('index.html')
self.response.write(template.render(tpi_vars))
def post(self):
opt=self.request.get("opt", allow_multiple=True)
session=get_current_session()
session['opt']=opt
I want to store checked checkboxes and get them. How can I make this possible?
Upvotes: 0
Views: 207
Reputation: 882231
Your Python code seems correct, apart from one weird bug whereby the line using jinja_environment
is concatenated to the previous one (?!).
Your Jinja template seems wrong as it doesn't look in the environment, nor does it mark any checkbox as checked
. I would recommend something like:
<input type="checkbox" name="opts" value="opt1" {{ops.get('opt1','')}>
option 1<br>
and so on -- the double braces to check into the environment, and a dictionary ops
that you could prepare on the Python side.
Right now what you get as opt
is a list such as e.g ['opt1'] if that's the only checked checkbox at post time. You could deal with that in the Jinja side, but it's easier on the Python side, I think. So, instead of:
tpi_vars={"opt":opt}
I'd do:
tpi_vars={'ops': dict.fromkeys(opt, 'checked')}
Of course, you don't have to do it just before you render the Jinja2 template -- you could do this list-to-dict translation at any time. But since it is about presentation issues, this seems a good place for it.
Upvotes: 1