Rendering Data-Frame to html template in table view using Django Framework

In Django, It is easy to render the HTML templates by setting URLs of respective HTML pages. Here we will let to know about how we can work with DataFrame to modify them for table view in the HTML template or web-pages, and for that, we have to use ‘render’ and ‘HttpResponse’ functions to manipulate the data inside the DataFrame.

Sample DataFrame:

Methods to render dataframe to html template –

  • Using pandas.DataFrame.to_html(): By using this inbuilt function ‘to_html()‘ to convert DataFrame into HTML template. After using this method, the overall DataFrame is converted to ‘table’ html element, while the name of each column are transformed into ‘thead’ tag of table head. Whereas, each row of the DataFrame is transformed into ‘tr’ tag of table row element in HTML template page.

    views.py



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    from django.shortcuts import HttpResponse
    import pandas as pd
      
    def Table(request):
        df = pd.read_csv("tableview/static/csv/20_Startups.csv")
        #'tableview/static/csv/20_Startups.csv' is the django 
        # directory where csv file exist.
        # Manipulate DataFrame using to_html() function
        geeks_object = df.to_html()
      
        return HttpResponse(geeks_object)

    chevron_right

    
    

    urls.py

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    """
    The `urlpatterns` list routes URLs to views. For more information please see:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  path('', views.home, name ='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  path('', Home.as_view(), name ='home')
    Including another URLconf
        1. Import the include() function: from django.urls import include, path
        2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    """
    from django.contrib import admin
    from django.urls import path
    from tableview import views
      
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', views.Table, name ="table"),
    ]

    chevron_right

    
    

    Output:

  • Parsing DataFrame into Json objects and render into bootstrap template: Here we use proper bootstrap template and get a table view using render() function.

    views.py

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Write Python3 code here
    from django.shortcuts import render
    import pandas as pd
    import json
      
    # Create your views here.
    def Table(request):
        df = pd.read_csv("tableview/static/csv/20_Startups.csv")
      
        # parsing the DataFrame in json format.
        json_records = df.reset_index().to_json(orient ='records')
        data = []
        data = json.loads(json_records)
        context = {'d': data}
      
        return render(request, 'table.html', context)

    chevron_right

    
    

    table.html (‘Bootstrap HTML Template’)

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!-- Write HTML code here -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <title>TableView - Startup</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
      
    <div class="container">
      <h2 class="text-center"><u>20 - Startups Table</u></h2><br>            
      <table class="table table-dark table-striped">
        <thead>
          <tr>
            <th>R&D Spend</th>
            <th>Administration</th>
            <th>Marketing Spend</th>
            <th>State</th>
            <th>Profit</th>
          </tr>
        </thead>
        <tbody>
        <!-- jinja2 Technique -->
        {% if d %}  
        {% for i in d %}
          <tr>
            <td>{{i.RD_Spend}}</td>
            <td>{{i.Administration}}</td>
            <td>{{i.Marketing_Spend}}</td>
            <td>{{i.State}}</td>
            <td>{{i.Profit}}</td>
          </tr>
        {% endfor %}
        {% endif %}
        </tbody>
      </table>
    </div>
      
    </body>
    </html>

    chevron_right

    
    

    Output:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.