2

我不知道我在 Google App Engine 中遇到以下代码错误。我想列出模型对象的所有元素。当我运行代码时,出现以下错误。谁能向我解释为什么我会收到这个错误?

错误:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
    rv = self.handle_exception(request, response, e)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__
    rv = self.router.dispatch(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "C:\Users\evalentini\Desktop\Personal\Udacity Web Development Class\logintest\main.py", line 143, in get
    self.render("userlist.html", users=users)
  File "C:\Users\evalentini\Desktop\Personal\Udacity Web Development Class\logintest\main.py", line 73, in render
    self.write(render_str(template, **kw))
  File "C:\Users\evalentini\Desktop\Personal\Udacity Web Development Class\logintest\main.py", line 32, in render_str
    return t.render(params)
  File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 894, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\evalentini\Desktop\Personal\Udacity Web Development Class\logintest\templates\userlist.html", line 3, in top-level template code
    {% for user in users: %}
TypeError: 'User' object is not iterable

我编写了 requestHandler 对象(ListNames),它应该列出名称(下面的代码):

类列表名称(博客处理程序):

def get(self):
    users=User.all().get()
    self.render("userlist.html", users=users)

它使用我的用户模型:

class User(db.Model):
    name=db.StringProperty(required=True)
    pwd=db.StringProperty(required=True)
    email=db.StringProperty(required=True)

和一个名为 render 的函数从 jinja 模板渲染页面:

def render_str(template, **params):<br>
    t=jinja_env.get_template(template)
    <br>return t.render(params)

Jinja 模板如下:

<html>

{% for user in users: %}
    <div style="{border: 1px solid; border-color: blue; padding: 1px;}">
        {{user.name}}
    </div>
{% endfor %}
</html>
4

1 回答 1

4

您只获得 1 个用户

users=User.all().get()

这将返回第一个实体

您需要使用 fetch() 来返回用户列表

users=User.all().fetch(1000)

或传入查询,如:

users=User.all()

最后一个不是最佳选择,因为它可能会返回太多用户,这会影响您的应用程序性能甚至更糟。

于 2012-06-07T00:44:09.823 回答