A story that I wanted to display the division result (%) on HTML with an application using django [Beginner learns python with a reference book in one hand]

Introduction

Using Takashi Otaka, "Learning by Moving! Introduction to Python Django Development" I'm a beginner who started learning python and Django.

I've been studying programming for about 4 months using ruby / rails, When I changed jobs as an engineer, I decided to use python, so I started studying with this book in my hand.

Since I am a de-class amateur, I would be very grateful if you could comment on supplements and suggestions.

Overview

I want to display the division result (percentage) on the HTML of the app created by django. I also want you to round it off.

What I tried

I decided to make my own filter. Below is a quote from the __old __ver. Documentation. https://djangoproject.jp/doc/ja/1.0/howto/custom-template-tags.html

The Django template system comes with a wide range of built-in tags and filters to help you solve problems with your application's presentation logic. However, the core template tag primitives alone may not meet your needs. You can extend the template engine for those cases. You can write your own tags and filters in Python and use the {% load%} tag on the template. Code placement Put your custom template tags and filters inside your Django application. If it's related to an existing application, you can bundle it with that application. If not, create a new application to hold the code. You must put the templatetags directory inside your application. Place this directory in the same hierarchy as models.py, views.py, etc. If you don't have templatetags, create one. Don't forget to put init.py in your directory and package it. Place your custom tags and filters under the templatetags directory. Name the module file the name you will use later when loading the tags. So be careful when deciding on a name so that it doesn't conflict with custom tags or filters in other applications.

① Create the templatetags directory and the following files

Have a directory file that describes your custom templates and filters. Keep the hierarchy in the same hierarchy as models.py and views.py.

views.py
models.py
.
.
.
templatetags
 ├─ __init__.py
 └─ hoge_tag.py

② Describe the division process in hoge_tag.py

Round with the round function. value → number to be divided args → number to divide Name the filter division.

hoge_tag.py


from django import template

register = template.Library()

@register.filter(name="division")
def division(value, args):
    return round(value / args * 100, 2)

The last "2" defines how many decimal places to leave after rounding. __ * However, you need to be careful about how to round numbers using the round function. __

The behavior of round () on floating point numbers may be surprising: for example, round (2.675, 2) gives 2.67 instead of 2.68 as expected. This is not a bug: This is the result of most decimals not being accurately represented by floating point numbers.

For details, refer to the following. https://docs.python.org/ja/3/library/functions.html#round

③ Read hoge_tag.py in HTML

Add the following so that the calculation formula can be read in the HTML that you want to use the above calculation formula.

fuga.html


{% load hoge_tag %}

All you have to do is display it.

fuga.html


{{ hoge | division:fuga}}%

If you enter numerical values (variables are possible) in "hoge" and "fuga", you can see the rose-colored world.

Great reference article

-Create your own template tags and filters -Built-in functions (python official)I want to process multiplication with [Django] templates → I don't have it, so I create a filter to handle it

Recommended Posts

A story that I wanted to display the division result (%) on HTML with an application using django [Beginner learns python with a reference book in one hand]
A story that I wanted to do a function like before_action used in rails with django [Beginner learns python with a reference book]
A story that I did not know how to load a mixin when making a front with the django app [Beginners learn python with a reference book in one hand]
A story that didn't work when I tried to log in with the Python requests module
I made a web application in Python that converts Markdown to HTML
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
I enjoyed writing with a single stroke on the self-avoiding random walk ~ Using python with reference to Computational Physics I (Asakura Shoten) ~
I made a class to get the analysis result by MeCab in ndarray with python
A super introduction to Django by Python beginners! Part 1 I tried to display an HTML page that only says "Hello World"
I made a program to collect images in tweets that I liked on twitter with Python
A story that I had a hard time trying to create an "app that converts images like paintings" with the first web application
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
Note that I was addicted to accessing the DB with Python's mysql.connector using a web application.
[Python] I tried to make a simple program that works on the command line using argparse.
I wanted to solve the ABC164 A ~ D problem with Python
I tried to make a todo application using bottle with python
order_by ('-created_at') ← What is "ー"? ?? ?? [Beginner learns python with a reference book]
A story about converting HTML to PDF with WeasyPrint + matplotlib and embedding graphs [Beginners learn python with a reference book]
The story of making a web application that records extensive reading with Django
A story that I was addicted to when I made SFTP communication with python
To automatically send an email with an attachment using the Gmail API in Python
Introducing the book "Creating a profitable AI with Python" that allows you to learn machine learning in the shortest course
Explaining how to make LINE BOT in the world's easiest way (2) [Preparing a bot application in a local environment with Django in Python]
I want to display the progress in Python!
A story that I wanted to realize the identification of parking lot fullness information using images obtained with a Web camera and Raspberry Pi and deep learning.
A story that was convenient when I tried using the python ip address module
A story that got stuck when trying to upgrade the Python version on GCE
A note on the library implementation that explores hyperparameters using Bayesian optimization in Python
A story about a Python beginner trying to get Google search results using the API
When writing to a csv file with python, a story that I made a mistake and did not meet the delivery date
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
(Python) Try to develop a web application using Django
I want to work with a robot in python.
A memo that I touched the Datastore with python
I drew a Python graph using public data on the number of patients positive for the new coronavirus (COVID-19) in Tokyo + with a link to the national version of practice data
[Python] I tried to make an application that calculates salary according to working hours with tkinter
I built an application with Lambda that notifies LINE of "likes" using the Qiita API
A story that makes it easy to estimate the living area using Elasticsearch and Python
A story that went missing when I specified a path starting with a tilde (~) in python open
I tried to automate "one heart even if separated" using a genetic algorithm in Python
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
[Shell startup] I tried to display the shell on the TV with a cheap Linux board G-cluster
I also tried to imitate the function monad and State monad with a generator in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I want to make a voice changer using Python and SPTK with reference to a famous site
I wanted to solve the Panasonic Programming Contest 2020 with Python
How to convert an array to a dictionary with Python [Application]
I made a simple book application with python + Flask ~ Introduction ~
How to generate a query using the IN operator in Django
I can't log in to the admin page with Django3
I tried to make a stopwatch using tkinter in python
I want to extract an arbitrary URL from the character string of the html source with python
I made something with python that NOW LOADING moves from left to right on the terminal
I tried using "Asciichart Py" which can draw a beautiful graph on the console with Python.
The story of creating a bot that displays active members in a specific channel of slack with python