I tried to create a table only with Django

Background You want to receive multiple elements in an array on the display side and display them using <table> </table>. If you want to display in 5 columns, there will be a scene where you divide the columns somewhere.

If it is javascript

    var i = 0;
    var cols = 5; //Number of columns
    var row_ele = NaN;

    for (key in dataset){
        if (i == 0){
            row_ele = NaN;
            row_ele = $("<tr></tr>");
        } 

        var cell = $("<td></td>");
        cell.text(dataset[key]);
        row_ele.append(cell);

        if (i == cols - 1){
            i = 0;
            $("table").append(row_ele);
        } else {
            i++;
        }
    }

I think I can write.

However, standard Django doesn't allow calculations within templates. Here, I will write the calculation method while introducing the django-mathfilters module.

dataset & list view As a sample example, we are using about 100 words that have become trendy on twitter.

views.py


from django.views.generic import TemplateView

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        words = ['Total stop','#The best height difference between boyfriend and girlfriend is 13 cm','Start work','Tomomi Itano','Tomomi Marriage'
                ,'New entry of foreigners','Business people','#Solution King and Prince','#Refreshing','#Asaichi'
                ,'Devil voice actor','Remote live appearance','Student mobilization','#Ochoyan','crowded train'
                ,'Mr. Koike's mismanagement','Beginning of work','graduate student','Teacher's medical field','Nursing University'
                ,'Mr. Namikawa','Strawberry day','Complete victory S','Director Takatsu','Declaration issuance request'
                ,'Mr. Asanuma','Marriage registration witness column','Yasushi Akimoto','Chiyo-chan','Nakayama 1R'
                ,'Touken Danshi rice','Keiji-kun','Toyosu Market','Starting work','Minotauros dish'
                ,'Entering the cold','High school soccer emergency declaration','Go day','England','Rookie section'
                ,'Strawberry day','Illegal employment / guarantee undeclared','Manba-chan','Shizuoka held','Remarks by President of Asahikawa Medical University'
                ,'Telework','Woman Rush Hour Muramoto','Sushi Zanmai','Saitama self-restraint','Bluefin tuna from Oma'
                ,'Devil voice actor','Beginning of work','graduate student','Teacher's medical field','Strawberry day'
                ,'Nursing University','Mr. Namikawa','Complete victory S','Declaration issuance request','Director Takatsu'
                ,'Marriage registration witness column','Yasushi Akimoto','Mr. Asanuma','Chiyo-chan','Keiji-kun'
                ,'Touken Danshi rice','Toyosu Market','Starting work','Minotauros dish','England'
                ,'Go day','Entering the cold','Manba-chan','Rookie section','Strawberry day'
                ,'High school soccer emergency declaration','Remarks by President of Asahikawa Medical University','Shizuoka held','Bluefin tuna from Oma'
                ,'Saitama self-restraint','Telework','Sushi Zanmai','Itano','Illegal employment / guarantee undeclared'
                ,'Get addicted','Total stop','Start work','#The best height difference between boyfriend and girlfriend is 13 cm','Tomomi Itano'
                ,'Tomomi Marriage','New entry of foreigners','Business people','#Solution King and Prince','#Ochoyan'
                ,'#Refreshing','#Asaichi','Remote live appearance','Mr. Koike's mismanagement','Student mobilization'
                ,'crowded train']
        context["tweets"] = words 
        return context

index.html


<!DOCTYPE HTML>

<html>
    <head> </head>
    <body> 
        <h1> mathfilter </h1>
            <ul>
            {% for item in tweets %}
                <li>{{item}}</li>
            {% endfor %}
            </ul>
    </body>
</html>

I store an array containing tweet words using tweets as a key, send it to the view side, and draw each element using the for statement with {% for item in tweets%} {% endfor%} I will.

The display will be a one-column list display.

add module

Then add django-mathfilters. Install the module with pip and add the application with settings.py.

pip3 install django-mathfilters

settings.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mathfilters'
]

improvement

<!DOCTYPE HTML>
{% load mathfilters %} <!--Defined in html-->

<html>
    <head> </head>
    <body> 
        <h1> mathfilter </h1>
            <table>
            {% for item in tweets %}
                {% with index=forloop.counter0 %} <!--Get index-->
                    {% if index|mod:5 == 0 %} <tr> {% endif %}
                        <td>
                            {{item}}
                        </td>
                    {% if index|mod:5 == 4 %} </tr> {% endif %}
                {% endwith %}
            {% endfor %}
            </table>
    </body>
</html>

If you set {% with index = forloop.counter0%} {% endwith%}, you can get the index like for i, item in enumerate (range (...)): print (i). This feature is standard in Django. index | mod: 5 will calculate the remainder of the numbers with the function of mathfilters that I would like to introduce this time. In addition to this, you can perform four arithmetic operations by adding addition`` sub mul`` div. Here, if index% 5 == 0, add<tr>to the beginning, and if index% 5 == 4, add </tr> to the end.

The browser is displayed in 5 columns of the table as shown below. capture.png

Reference -How to perform arithmetic processing with Django template -Display loop counter number in Django Template -How to subtract (subtract) in a [Django] template

Recommended Posts

I tried to create a table only with Django
I tried to automatically create a report with Markov chain
I tried to create a linebot (implementation)
I tried to create a linebot (preparation)
I tried to create a list of prime numbers with python
I tried to create Bulls and Cows with a shell program
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
Create a homepage with django
I tried to create a plug-in with HULFT IoT Edge Streaming [Development] (2/3)
I tried to create a plug-in with HULFT IoT Edge Streaming [Execution] (3/3)
I tried to create CSV upload, data processing, download function with Django
I tried to send a registration completion email from Gmail with django.
[Outlook] I tried to automatically create a daily report email with Python
I tried to create a plug-in with HULFT IoT Edge Streaming [Setup] (1/3)
I tried to draw a route map with Python
I tried to automatically generate a password with Python3
I want to manually create a legend with matplotlib
When I tried to create a virtual environment with Python, it didn't work
I tried to easily create a fully automatic attendance system with Selenium + Python
I tried to create a button for Slack with Raspberry Pi + Tact Switch
I tried to create a model with the sample of Amazon SageMaker Autopilot
I tried to create Quip API
Steps to create a Django project
Create a file uploader with Django
I tried to implement a volume moving average with Quantx
I want to make a blog editor with django admin
I made a command to generate a table comment in Django
I tried to solve a combination optimization problem with Qiskit
I tried to get started with Hy ・ Define a class
I tried to sort a random FizzBuzz column with bubble sort.
I tried to create a bot for PES event notification
I tried to divide with a deep learning language model
I tried to create an article in Wiki.js with SQLAlchemy
I tried to create a reinforcement learning environment for Othello with Open AI gym
[Python] I tried to automatically create a daily report of YWT with Outlook mail
I tried to create a class to search files with Python's Glob method in VBA
I tried scraping food recall information with Python to create a pandas data frame
[5th] I tried to make a certain authenticator-like tool with python
I tried to create a simple credit score by logistic regression.
I tried to make a system that fetches only deleted tweets
I tried to implement Autoencoder with TensorFlow
[2nd] I tried to make a certain authenticator-like tool with python
I tried to visualize AutoEncoder with TensorFlow
A memorandum when I tried to get it automatically with selenium
I tried to get started with Hy
I wanted to create a smart presentation with Jupyter Notebook + nbpresent
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
Rails users try to create a simple blog engine with Django
I tried to make a periodical process with Selenium and Python
I tried a functional language with Python
A note I was addicted to when creating a table with SQLAlchemy
I tried to make a 2channel post notification application with Python
I tried to implement CVAE with PyTorch
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
I tried to make a Web API
I tried to solve TSP with QAOA
[1st] I tried to make a certain authenticator-like tool with python
I tried Django
I tried to make a strange quote for Jojo with LSTM