Django custom filter definition and usage example

The example in this article describes the definition and usage of Django custom filters. Share for your reference, the details are as follows:

First, the introduction of custom filters

      A filter is actually a function that passes the field to be passed into a function, processes it, and returns a new value to display on the page. In actual development, the filter that comes with the system sometimes cannot meet our needs. time to customize

2. There are two ways to customize filters in Django

1. templatetagsCreate a separate py file in the component (App) 2. Create a separate
component (App) to store all the custom filters in the project

3. Create custom filters in components in the project

1. It can only be created in the installed component ( App) 2. It can only be created in the package
under the component (App) 3. The decorator must be used 4. Define a method, pass the value in for processing, and return a new value 5. Create custom filtertemplatetags
@register.filter

①. Create a poll.py file under the templatetags package

from django import template
register = template.Library()
@register.filter
def mycut(value,args):
  return value.replace(args,"")

6. Use custom filters

①. Import files first{% load poll %}

②. Use

{% load poll %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p>{{ msg | mycut:' '}}</p>
</body>
</html>

4. You can customize a component ( App) [because you don't need too many files, create one manually]

1. Manually create a package
2. Create a package in templatetagsthe package
3. settings.pyInject the created package into
4. templatetagsCreate files and functions
in 5. Use of filters (same as above)

V. Supplementary Instructions

@stringfilterIf it is a string operation, a modifier is generally introduced

from django import template
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.filter
def mycut(value,args):
  return value.replace(args,"")
@register.filter
@stringfilter
def mylower(value):
  return value.lower()

I hope that this article will help you in the Python programming of the Django framework.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325686677&siteId=291194637