The custom filter Djnago

step one

Created in the app where a templatetags包, note the definition of a python file in the bag, such as blog_tags. (If you put filters are written, found impossible, probably out of the question here, just in this folder, add one init(there are two underscores) files can be)

Step Two

Writing custom filters

from django import template
from article.models import Article

register = template.Library()


@register.simple_tag  # 还有其他类型的,我还没涉及到,想了解的话,自己可以查一下
def get_recent_article(num=3):
    return Article.objects.all().order_by("-post_time")[0:num]

Step Three

Front-end file used
to load the file name

{% load blog_tags %}

You can normally use a custom label

Published 141 original articles · won praise 131 · views 210 000 +

Guess you like

Origin blog.csdn.net/qq_41621362/article/details/102885110