dJudge
dJudge

Reputation: 186

CSV File into Django Template

I have an app that uploaded a file using the FileField(). Uploading the file works excellently but I have a problem on how to display the CSV file content into an HTML table where headings goes to the table header while the rows/lines of the CSV file goes to the appropriate cell in an HTML table.

For now i have a little success in retrieving the CSV file's columns. Here are the snippets.

Method:

# retrieve datafarame's columns
def get_columns(file):
    df = pd.read_csv(file)
    cols = df.columns
    return cols

HTML:

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
            <thead>
                <tr>
                    {% for col in columns %}
                    <th>{{ col }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                <tr>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                </tr>
            </tbody>
        </table>

Upvotes: 0

Views: 2098

Answers (2)

user13861994
user13861994

Reputation:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Detect Outliers</title>
    </head>
    <body>
        <button type="button">Upload</button> 
        <h1>Uploaded Data</h1> 
        <table border="1px"> 
            <tr> 
                {% for data in DataFrame %} 
                    <th>{{ data }}</th> 
                {% endfor %} 
         
                {% for _, record in DataFrame.iterrows %} 
                    <tr> 
                        {% for value in data %} 
                            <td>{{ value }}</td> 
                        {% endfor %} 
                    </tr> 
                {% endfor %} 
            </tr> 
        </table> 
    </body>
    </html>

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

If you are using pandas in the backend, then you can pass the dataframe.to_dict() from the view which will give you a list of dictionaries. You can iterate over the list of rows in your template.

views.py

def myview(request):
    df = pd.read_csv(file)
    return render(request, 'my_view.html', {'columns': df.columns, 'rows': df.to_dict('records')})

template.html

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
        <thead>
            <tr>
                {% for col in columns %}
                <th>{{ col }}</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for index, row in rows %}
                <tr>
                  <td>{{row.name}}</td>
                  <td>{{row.email</td>

                </tr>
             {% endfor %}
        </tbody>
    </table>

Upvotes: 3

Related Questions