SoFunction
Updated on 2024-11-20

Django Custom Filter Definition and Usage Examples

This article example describes Django custom filter definition and usage. Shared for your reference, as follows:

I. Introduction to customized filters

Previously we have introduced the filter is actually a function to pass over the field to a function, processing, return a new value to be displayed in the page, in the actual development of the system comes with the filter sometimes can not meet our needs when we have to customize the

Second, there are two ways to customize filters in Django

1. In the component (App) of thetemplatetagsCreate a separate py file
2, create a separate component (App) used to store all the custom filters in the project

Third, create custom filters in the components in the project

1、Only in the installed components (Apphit the nail on the head
2、Only under the component (App)templatetagsCreated within the package
3. Modifiers must be used@
4. Define a method, pass in the value to be processed, return the new value
5、Create customized filters

①. Create a file under the templatetags package.

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

6. Use of customized filters

①. Introduce the file 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>

Fourth, you can customize a component (App) [created one manually since not too many files were needed]

1, manually create a package
2. Create a package in thetemplatetagspackages
3. Place this created package in theembedded in
4. IntemplatetagsCreate files and functions in
5, the use of filters (the same as above)

V. Supplementary notes

In the case of string manipulation generally introduces a@stringfiltermodifier (computing)

from django import template
from  import stringfilter
register = ()
@
def mycut(value,args):
  return (args,"")
@
@stringfilter
def mylower(value):
  return ()

I hope that the description of this article will help you in Python Programming for Django Framework.