Flask / Python3.7 jinja2.exceptions.UndefinedError:'list object'没有属性'page'

问题描述 投票:0回答:1

我有一个简单的Flask端点,从sqlite3获取数据,并将结果拆分为页面。

即使是空数据,它也应该显示空表。

我在一个新的VPS上安装了python3.7,安装了这些要求,但是现在我收到了这个错误,我从来没有这样做,当我在本地运行相同的代码时就不会发生这种错误。

File "/bot/templates/show_items.html", line 17, in top-level template code
    </a>,<a href="{{ url_for('show_items', page=items.page) }}">Refresh</a>,<a href="./export/">Export All</a>,<a href="./deleteAll/">Del. All (watch out)</a>)
  File "/usr/local/lib/python3.7/site-packages/flask/helpers.py", line 345, in url_for
    force_external=external)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 1774, in build
    rv = self._partial_build(endpoint, values, method, append_unknown)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 1689, in _partial_build
    append_unknown)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 1697, in _partial_build
    rv = rule.build(values, append_unknown)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 809, in build
    add(self._converters[data].to_url(values[data]))
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 1034, in to_url
    value = self.num_convert(value)
jinja2.exceptions.UndefinedError: 'list object' has no attribute 'page'

失败的模板:

<h3>(<a href = "{{ url_for('new') }}">Add Items
     </a>,<a href="{{ url_for('show_items', page=items.page) }}">Refresh</a>,<a href="./export/">Export All</a>,<a href="./delet$

   </h3>

终点:

@app.route("/", defaults={'page': 1}, methods=["GET", "POST"])
@app.route("/<int:page>/", methods=["GET", "POST"])
def show_items(page):

  try:

    itemss = items.query.order_by("lastUpdate desc, idI desc").paginate(page, 10)
  except:
    itemss = []
  return render_template('show_items.html', items = itemss )

我不经意地检查了其他堆栈问题,遗憾的是没有任何相关内容,我试过但是当数据库充满时它没有显示数据:jinja2.exceptions.UndefinedError: 'str object' has no attribute 'username'

ubuntu flask jinja2 python-3.7
1个回答
0
投票

代码必须输入except块,因此items是一个空列表,而不是分页对象。在模板中放置一个if块来处理没有项目的情况,你将摆脱错误。

<h3>(<a href = "{{ url_for('new') }}">Add Items</a>,

    {% if not items %}
    <a href="{{ request.url }}">Refresh</a>,
    {% else %}
    <a href="{{ url_for('show_items', page=items.page) }}">Refresh</a>,
    {% endif %}

     <a href="./export/">Export All</a>,<a href="./delet$}


 </h3>
© www.soinside.com 2019 - 2024. All rights reserved.