基本上我试图显示联系人列表,当用户点击其中一个时,联系人会显示在另一个div中。
我解决问题的方法是使用密钥隐藏输入,然后在处理程序中使用NDB API通过其密钥检索联系人对象。但是我无法检索到该对象。我尝试了一些不同的解决方案,比如制作一个Contact.query()等等。到目前为止,我已经失败了。
这是我的联系人型号:
class Contact(ndb.Model):
cname = ndb.StringProperty(indexed=False)
phone = ndb.StringProperty(indexed=False)
email = ndb.StringProperty(indexed=False)
date_add = ndb.DateTimeProperty(auto_now_add=True)
在模板中,我遍历联系人列表,每个联系人都是一个表单:
{% for contact in contacts %}
<li>
<form method="get">
<input type="hidden" name="act" value="display"/>
<input type="hidden" name="key" value="{{contact.key.urlsafe()}}" />
<input type="submit" value="{{ contact.cname }}"/>
</form>
</li>
{% endfor %}
这是我的请求处理程序
class Profile(webapp2.RequestHandler):
def get(self):
if users.get_current_user():
contacts = get_contacts(users.get_current_user().user_id())
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
template = JINJA_ENVIRONMENT.get_template('profile.html')
template_values={
'url':url,
'url_linktext':url_linktext,
'contacts':contacts,
}
if contacts:
if self.request.get('act') == 'display':
dcontact = get_contact(self.request.get("key"))
else:
dcontact = contacts[0]
template_values['dcontact'] = dcontact
self.response.write(template.render(template_values))
else:
self.redirect('/')
这是我对get_contact()函数的最后一种方法,也是这种情况下的主要问题:
def get_contact(key):
return Contact.get_by_id(key)
我也很感激有关这种情况的一些建议。我在Django做过类似的事情,对我来说这更容易。我在webapp2和GAE中仍然有点迷失
答案 0 :(得分:1)
好吧,我非常喜欢它。对于处于类似情况的人,我建议阅读NDB Entities and Keys这是关于在NDB API中使用Key的一个很好的文档。在我问这个问题之后我找到了它:/
get_contact函数()将如下所示:
def get_contact(key):
ckey = ndb.Key(urlsafe=key)
return ckey.get()
答案 1 :(得分:0)
从数据存储中检索对象的另一种方法是使用id 你已经尝试过了,但这应该是这样的
def get_contact(key):
return Contact.get_by_id(key.id())
一个键有一个.id()
属性可以返回id,这样就可以获得一个带有键的对象