Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a Table in Django from Database

How do you display the information from a database table in a table format on a webpage? Is there a simple way to do this in django or does it require a more complicated approach. More specifically, how do you pretty much port over the columns and rows in a database table to a visual table that can be seen from a url?

like image 311
randrumree Avatar asked Sep 02 '11 17:09

randrumree


People also ask

How are tables created in Django?

Django made creating the tables in the database very simple with its built-in ORM. To create table in the database with django is to create a django model with all required fields and then create migrations and apply them.


2 Answers

The easiest way is to use a for loop template tag.

Given the view:

def MyView(request):
    ...
    query_results = YourModel.objects.all()
    ...
    #return a response to your template and add query_results to the context

You can add a snippet like this your template...

<table>
    <tr>
        <th>Field 1</th>
        ...
        <th>Field N</th>
    </tr>
    {% for item in query_results %}
    <tr> 
        <td>{{ item.field1 }}</td>
        ...
        <td>{{ item.fieldN }}</td>
    </tr>
    {% endfor %}
</table>

This is all covered in Part 3 of the Django tutorial. And here's Part 1 if you need to start there.

like image 96
j_syk Avatar answered Sep 23 '22 23:09

j_syk


$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>
like image 22
Anar Ali Avatar answered Sep 21 '22 23:09

Anar Ali