How to implement Rails helper-like functionality in Django

Introduction

This article is a personal note when I first created an app in Django and looked for features like Rails helper.

environment

Python(3.6.2) Django(2.1.7)

Custom template filter

Rails helper can call the method defined in helper on the view side. In Django as well, I investigated whether the method defined in another file can be called on the template side, and it seems that it can be realized by creating a custom template filter.

Implementation method

You can create a custom template filter by following the steps below.

1. Create a directory called templatetags

Create a directory called templatetags in the app directory of the template where you want to install the custom filter.

2. Place \ _ \ _ init__.py in templatetags

Place \ _ \ _ init__.py to modularize the files you create in the templatetags directory.

3. Create a file that defines custom template filters in templatetags

First call the template library.

from django import template
register = template.Library()

Register your own custom template filter in this library. Now you can call the method created on the template side.

@register.filter
def transrate_media_number(var):
  if var == 0:
    media_name = 'Gurunavi'
  elif var == 1:
    media_name = 'eating log'
  elif var == 2:
    media_name = 'Hot pepper'
  else:
    media_name = 'Other'
  return media_name

custom_filter.py


from django import template
register = template.Library()

@register.filter
def transrate_media_number(var):
  if var == 0:
    media_name = 'Gurunavi'
  elif var == 1:
    media_name = 'eating log'
  elif var == 2:
    media_name = 'Hot pepper'
  else:
    media_name = 'Other'
  return media_name

The end result is a directory structure like this:

app/  ├ models.py  ├ templatetags/  │ ├ __init__.py  │ └ custom_filter.py  └ views.py

4. Call on the template side

First, load the custom template filter created from the template.

  - load custom_filter

The loaded custom template filter can be used in the following form.

  {{argument|Custom template filter name}}

python:template_file.html.haml


- load custom_filter

%table
  {% for data in datum %}
    %tr
      %td
        {{ data.take_at }}
      %td
        # {{argument|Custom template filter name}}
        {{ data.media_number | transrate_media_number }}

That's it.

Recommended Posts

How to implement Rails helper-like functionality in Django
Implement follow functionality in Django
How to reflect CSS in Django
How to delete expired sessions in Django
How to implement nested serializer in drf-flex-fields
How to do Server-Sent Events in Django
How to implement Scroll View in pythonista 1
How to convert DateTimeField format in Django
How to implement Discord Slash Command in Python
How to implement shared memory in Python (mmap.mmap)
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
How to implement a gradient picker in Houdini
How to implement "named_scope" of RubyOnRails with Django
Implement JWT login functionality in Django REST framework
How to create a Rest Api in Django
How to get multiple model objects randomly in Django
How to use bootstrap in Django generic class view
How to upload files in Django generic class view
How to use Decorator in Django and how to make it
How to reference static files in a Django project
How to develop in Python
How to write custom validations in the Django REST Framework
How to use Laravel-like ORM / query builder Orator in Django
How to check ORM behavior in one file with django
How to update user information when logging in to Django RemoteUserMiddleware
How to temporarily implement a progress bar in a scripting language
[Django] How to give input values in advance with ModelForm
How to generate a query using the IN operator in Django
How to implement Python EXE for Windows in Docker container
In Django, how to abbreviate the long displayed string as ....
[Python] How to do PCA in Python
How to handle session in SQLAlchemy
[Rails] How to display Google Map
[Django] How to test Form [TDD]
How to use classes in Theano
How to write soberly in pandas
How to collect images in Python
Errors related to memcached in django
How to update Spyder in Anaconda
How to use SQLite in Python
How to convert 0.5 to 1056964608 in one shot
How to get started with Django
How to kill processes in bulk
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to write Django1.9 environment-independent wsgi.py
How to run TensorFlow 1.0 code in 2.0
How to handle Japanese in Python
How to log in to Docker + NGINX
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to call PyTorch in Julia
[For beginners] How to implement O'reilly sample code in Google Colab
How to implement Java code in the background of RedHat (LinuxONE)
[Django] How to read variables / constants defined in an external file
How to deploy a Django app on heroku in just 5 minutes
How to do arithmetic with Django template
I tried to implement PLSA in Python