【问题标题】:AttributeError: 'list' object has no attribute 'product_img' Python, Flask, SQLiteAttributeError:'list'对象没有属性'product_img' Python,Flask,SQLite
【发布时间】:2021-02-08 15:56:28
【问题描述】:

我正在尝试在来自 SQLite 数据库的模板上显示文本和图像。 数据库模型:

class NewProduct(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    product_name = db.Column(db.String(100), nullable=False)
    product_description = db.Column(db.String(200), nullable=False)
    product_date = db.Column(db.DateTime, default=datetime.utcnow)
    product_img = db.Column(db.BLOB())

    def __repr__(self):
        return '<NewProduct %r>' % self.id

在 .html 中显示来自 db 的信息的功能:

@app.route('/products')
def products():
    products = NewProduct.query.order_by(NewProduct.product_date.desc()).all()
    product_img = b64encode(products.product_img).decode('utf-8')
    return render_template('products.html', products=products, image=product_img)

HTML:

<body>
{% if products|length > 0 %}

    {% for el in products %}
        <p>Name: {{ el.product_name }}</p>
        <p>Description: {{ el.product_description }}</p>
        <p>Image: </p> <img src="data:;base64,{{ image }}">
        <p>Date: {{ el.product_date }}</p>
    {% endfor %}

{% else %}
    <p>There are have no products</p>
{% endif %}

所以,我收到一个错误:AttributeError: 'list' object has no attribute 'product_img' in line product_img = b64encode(products.product_img).decode('utf-8')

我这样做是为了answer。但我无论如何都会得到这个错误。我在做什么,我该如何解决?

【问题讨论】:

    标签: python html sqlite flask


    【解决方案1】:

    products 是一个列表,因此 products.product_img 行会引发您面临的错误。如果您需要将图像转换为其他内容,则需要遍历 products 并修改每个产品的图像。

    【讨论】:

      【解决方案2】:

      您正在尝试访问product_img 以获得products 的列表,而不是单个对象。您需要遍历对象并更新每个对象的值:

      @app.route('/products')
      def products():
          products = NewProduct.query.order_by(NewProduct.product_date.desc()).all()
          for product in products:
              product.product_img = b64encode(product.product_img).decode('utf-8')
          return render_template('products.html', products=products)
      

      然后更新您的模板以从 product 对象中获取值:

      <body>
      {% if products|length > 0 %}
      
          {% for el in products %}
              <p>Name: {{ el.product_name }}</p>
              <p>Description: {{ el.product_description }}</p>
              <p>Image: </p> <img src="data:;base64,{{ el.product_img }}">
              <p>Date: {{ el.product_date }}</p>
          {% endfor %}
      
      {% else %}
          <p>There are have no products</p>
      {% endif %}
      

      我还建议从您的变量中删除前缀 product_,因为它似乎是多余的,并且会降低您的代码的可读性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-04
        • 2023-02-15
        • 2022-11-28
        • 2013-07-19
        • 1970-01-01
        • 1970-01-01
        • 2014-11-11
        相关资源
        最近更新 更多