Home > Software engineering >  Adding rows and columns to HTML table with Django
Adding rows and columns to HTML table with Django

Time:08-24

I have a problem. Consider an HTML table and it has rows and columns. I want to add a new row or column when I want it and I want it to be a record in the database. And I want to do this with django. What should I do? I think I need to use django_table2 but I don't know how. I would be glad if you write a code sample. Thank you)

CodePudding user response:

Say you have a model, you could get a list of objects like so;

def my_view(request):
    context = {'object_list':MyModel.objects.all()}
    return render(request, 'mypage.html', context)

Then in the template, you could do a few things to create tables: Either, fully generate the table with Django, like so:

{% for object in object_list %}
    <tr>
        <td>{{object.data}}</td>
        <td>{{object.data}}</td>
        <td>{{object.data}}</td>
    </tr>
{% endfor %}

This would create a new row for every object.

Another solution is:

{% for object in object_list %}
    //Create row for every object
    <tr>
        {% for data in object.get_field_data %}
            // Create column for every field in object
            <td>{{data}}</td>
        {% endfor %}
    </tr>
{% endfor %}

Where get_field_data would be defined as a method on the model like so:

def get_field_data(self):
    datalist = []
    for field in self._meta.get_fields():
        datalist.append(getattr(self, field.name))
    return datalist

You could then even implement some checks on the get_field_data, for example, you could exclude fields.

def get_field_data(self):
    datalist = []
    for field in self._meta.get_fields():
        if field.name != 'id':
            datalist.append(getattr(self, field.name))
    return datalist

CodePudding user response:

You don't need to use any external package, you can do this easily by using the Django Template Language

Here is a code example using a ListView

# views.py

from django.views.generic import ListView

class ItemListView(ListView):
    template_name = 'mytable.html'
    model = MyModel
    context_object_name = 'item_list'
<!-- mytable.html -->
...
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody> 
        {% for item in item_list %}
            <tr>
                <td>{{ item.name }}</td>
                <td>{{ item.amount }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
...

In this way your template will have access to a list of objects called item_list which corresponds exactly to the records in the database table. You can cycle that list/queryset using a for loop that will automatically wrap that content in the html needed to make it part of the table.

  • Related