GPA
GPA

Reputation: 111

IndexError: list index out of range python (flask)

I am making python app and I wanted to know why my program display IndexError: list index out of range. I wanted to create flask app which displays data from database.

Flask:

@app.route('/', methods=['POST','GET'])
def displaytask():
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM tasks")
    data = mycursor.fetchall()
    empty_table=false
    if data[0][0]==0:
          empty_table=true
    return render_template('index.html', data=data, value=empty_table)

It displays data only if they are already inserted if database is empty then error message show.

Error message: if data[0][0]==0: IndexError: list index out of range

I wanted to display data in jinja blocks:

   {% for row in data %}
        {% if value == true %}
           <li><span class='text'>No Record Found.</span></li>
        {% endif %}
        <li><span class="text">{{ row[1] }}</span>
         <i id="removeBtn" class="icon fa fa-trash"></i>
        </li>
   {% endfor %}

Upvotes: 0

Views: 2551

Answers (2)

Hiroaki Genpati
Hiroaki Genpati

Reputation: 79

if you just wanted check the data is null of not, just passing the data variable to template, and check with jinja. So the jinja template like this:

{% if data %}
{% for row in data %}
<li>
    <span class="text">{{ row[1] }}</span>
    <i id="removeBtn" class="icon fa fa-trash"></i>
</li>
{% endfor %}
{% else %}
<li><span class='text'>No Record Found.</span></li>
{% endif %}

more for tests in : https://jinja2docs.readthedocs.io/en/stable/templates.html#list-of-builtin-tests

Upvotes: 2

apr_1985
apr_1985

Reputation: 1962

If there is no data in the DB then data will be and empty list. If you then try to access it data[0][0] then you will get an out of range error as there isnt a position 0 in an empty list

In [420]: r = []
In [421]: r[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-421-8418cdc095ae> in <module>
----> 1 r[0]

IndexError: list index out of range

You will need to check if data is empty before trying to access it.

Upvotes: 2

Related Questions