Debug School

rakesh kumar
rakesh kumar

Posted on

How to display multiple table data into template file in django

Step 1: Define the models
First, let's define the models in your Django app. In models.py, add the following code:

from django.db import models

class City(models.Model):
    name = models.CharField(max_length=100)

class Item(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
Enter fullscreen mode Exit fullscreen mode

Step 1: Create a Django template file
In your Django app's templates directory, create a new HTML template file (e.g., items.html) to display the data:

<html>
<head>
    <title>Items</title>
</head>
<body>
    <h1>Items</h1>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>City</th>
                <th>Count</th>
            </tr>
        </thead>
        <tbody>
            {% for item in items %}
            <tr>
                <td>{{ item.name }}</td>
                <td>{{ item.city }}</td>
                <td>{{ item.count }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the above template, we use a simple HTML table to display the item name, city name, and count. We use a for loop to iterate over the items list, which we'll pass from the view.

Step 2: Update the view to render the template
In your Django view function, update it to render the template and pass the data to the template context:

from django.db.models import Count
from django.shortcuts import render

def get_items_with_city_count(request):
    items = Item.objects.values('name', 'city__name').annotate(count=Count('city__name'))
    items_list = list(items)

    context = {
        'items': items_list,
    }

    return render(request, 'items.html', context)
Enter fullscreen mode Exit fullscreen mode

In the updated code, we create a dictionary called context that contains the items list. We pass this context dictionary as the third argument to the render() function, along with the request, and specify the template name 'items.html'.

In the updated code, we create a dictionary called context that contains the items list. We pass this context dictionary as the third argument to the render() function, along with the request, and specify the template name 'items.html'.

Step 3: Define the URL pattern
In your urls.py, make sure you have the URL pattern set up to map the view function:

from django.urls import path
from .views import get_items_with_city_count

urlpatterns = [
    path('items/', get_items_with_city_count, name='get_items_with_city_count'),
]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)