显示选中的元素为选中的复选框
我正在尝试让用户从提供的爱好列表中选择他们的爱好,这个列表是以复选框的形式展示的。当用户选择了某些爱好后,这些爱好会被记录到用户表里。我希望我的复选框能显示用户的爱好:如果某个爱好被选中,它就会被勾选上;如果没有被选中,就不会勾选。用户可以通过勾选或取消勾选来更新他们的爱好。
我现在遇到的问题是,如何正确显示用户当前的爱好状态(勾选或不勾选),并根据这个状态更新用户的爱好表。
class InfoPage(BasePage):
title = 'One Macnica'
def get(self):
self.write_page_header()
hobbies_list = Hobby.all().fetch(100)
template_values = {"hobbies_list": hobbies_list}
path = os.path.join(os.path.dirname(__file__), 'templates')
path = os.path.join(path, 'hobby.html')
self.response.out.write(template.render(path, template_values))
self.write_page_footer()
def post(self):
self.write_page_header()
hobbies_list = Hobby.all().fetch(100)
if self.request.get("hobby"):
hobby_name = self.request.get('hobby')
new_hobby = Hobby(name=hobby_name.strip(), key_name = hobby_name.strip())
#fetch attendee and add new hobby
attendee_query = Attendee.gql('WHERE email = :1',
users.get_current_user().email())
attendee = attendee_query.fetch(1)
attendee = attendee.pop()
hobbies = attendee.hobbies
hobbies.append(new_hobby.key())
attendee.hobbies = hobbies
#eliminate the dupliate
hobbies = list(set(hobbies))
attendee.hobbies = hobbies
attendee.put()
template_values = {"hobbies_list": hobbies_list}
path = os.path.join(os.path.dirname(__file__), 'templates')
path = os.path.join(path, 'hobby.html')
self.response.out.write(template.render(path, template_values))
self.write_page_footer()
hobby.html 文件内容如下:
<h1 id="header">One Macnica</h1>
<p>Welcome to One Macnica, a place dedicated to connecting Macnica as 1.
</p>
<form name="hobby" action="/hobby" method="post">
{% for hobby in hobbies_list %}
<input type="checkbox" name = "{{hobby.name}}"/>{{hobby.name}}<br/>
{% endfor %}
<input type="submit" value="Select Hobbies">
</form>
我现在在考虑制作一个爱好复选框列表,这个列表会把所有的爱好和参与者的爱好进行比较,如果参与者的爱好在列表中,就返回勾选状态;如果不在,就返回空值。 我在实际编写代码时遇到了困难,不知道这样做是否是最好的方法。
任何帮助都会非常感谢。
3 个回答
1
最简单的方法是使用一个表单库,比如Django表单或者WTForms。因为这些库已经帮你处理好了很多表单相关的代码,所以你不需要自己写很多复杂的代码。
1
这个方法应该可以用来处理“checked”属性(其他的部分可以参考Steve的回答):
checked={{ hobby in user.hobbies and "checked" or "" }}
更新:
我已经很久没用过那个模板引擎了。我觉得问题出在你不能在{{ }}
里面使用in
、and
、or
这些关键字。
一个比较丑陋的解决办法是:
checked={% if hobby in user.hobbies %}"checked"{% else %}""{% endif %}
希望这对你有帮助。
1
{% for hobby in hobbies_list %}
<input type="checkbox" {% if hobby in user.hobbies %}checked="yes"{% endif %} name = "{{hobby.name}}"/>{{hobby.name}}<br/>
{% endfor %}
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。