[django] 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?

This question is related to django database

The answer is

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...

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

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

$ pip install django-tables2


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


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


from django.shortcuts import render

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


{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
        {% render_table istekler %}

If you want to table do following steps:-


def view_info(request):
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
       {% endfor %}

Questions with django tag:

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal? ImportError: No module named 'django.core.urlresolvers' How to set environment variables in PyCharm? How to get Django and ReactJS to work together? Invalid http_host header Django model "doesn't declare an explicit app_label" "Post Image data using POSTMAN" TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' Django URLs TypeError: view must be a callable or a list/tuple in the case of include() What is a NoReverseMatch error, and how do I fix it? What does on_delete do on Django models? Django values_list vs values Django download a file Uncaught TypeError: $(...).datepicker is not a function(anonymous function) Django - makemigrations - No changes detected How can I enable CORS on Django REST Framework Django - Did you forget to register or load this tag? Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet." Django Rest Framework -- no module named rest_framework How to revert the last migration? What's the difference between select_related and prefetch_related in Django ORM? Django: save() vs update() to update the database? Where does pip install its packages? no module named urllib.parse (How should I install it?) How to set the timezone in Django? You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application Django Model() vs Model.objects.create() NumPy array is not JSON serializable React Error: Target Container is not a DOM Element OperationalError, no such column. Django how to use python2.7 pip instead of default pip The view didn't return an HttpResponse object. It returned None instead You are trying to add a non-nullable field 'new_field' to userprofile without a default ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings 'NOT NULL constraint failed' after adding to models.py Django 1.7 - "No migrations to apply" when run migrate after makemigrations How to compare two JSON objects with the same elements in a different order equal? Django: OperationalError No Such Table Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet Mac OS X - EnvironmentError: mysql_config not found

Questions with database tag:

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str IN vs ANY operator in PostgreSQL How to execute raw queries with Laravel 5.1? How should I tackle --secure-file-priv in MySQL? How to use multiple databases in Laravel Why does Oracle not find oci.dll? How do I create a local database inside of Microsoft SQL Server 2014? How to change the default port of mysql from 3306 to 3360 Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES) How to change Oracle default data pump directory to import dumpfile? Using COALESCE to handle NULL values in PostgreSQL What is Hash and Range Primary Key? How to get item count from DynamoDB? Find duplicate records in MongoDB Django Model() vs Model.objects.create() Mongodb: Failed to connect to, reason: errno:10061 How can I rename column in laravel using migration? There is already an object named in the database How to list all databases in the mongo shell? Failed to connect to mysql at with user root access denied for user 'root'@'localhost'(using password:YES) Partial Dependency (Databases) Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong? ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend? Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES) The backend version is not supported to design database diagrams or tables Difference between partition key, composite key and clustering key in Cassandra? Backup/Restore a dockerized PostgreSQL database Can't connect to MySQL server on '' (10061) (2003) copy from one database to another using oracle sql developer - connection failed Best way to check for "empty or null value" ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How do I to insert data into an SQL table using C# as well as implement an upload function? Postgres - Transpose Rows to Columns How to update multiple columns in single update statement in DB2 How to increase MySQL connections(max_connections)? What are OLTP and OLAP. What is the difference between them? The ALTER TABLE statement conflicted with the FOREIGN KEY constraint Reset identity seed after deleting records in SQL Server How can I get all sequences in an Oracle database?