如何在Django中人性化标签?


人性化是指使某事物更人性化或更易于人类理解。人性化标签意味着使标签更容易被人理解。例如,1800000000 变为 18 亿,或 10000 变为 10,000。

可以实施一些简单的更改,以将标签转换为更易于阅读的格式。Django 提供了模板过滤器,可以为数据添加人性化元素,使其更具可读性。

要启用这些过滤器的使用,应将 **django.contrib.humanize** 添加到项目 settings.py 文件中的 INSTALLED_APPS 中。

INSTALLED_APPS = [
   'reglogin',
   'mlmodel',
   'django.contrib.humanize',
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles'
]

然后,应将 {%load humanize %} 添加到模板部分的标题部分。

现在,您已在项目中启用了 Django 提供的人性化过滤器。

有很多模板过滤器。下面列出了一些。

  • **apnumber** - 此过滤器将数字 1 到 9 拼写出来,对于所有其他数字,它返回相同的数字。例如:2 返回 two,12 返回 12

  • **intcomma** - 此过滤器将数字(整数或浮点数)转换为用逗号分隔的数字的字符串表示形式。例如:37900 变为 37,900

  • **intword** - 将大数转换为可读的文字表示形式。例如:8000000 变为 800 万,1200000000 变为 12 亿

  • **naturalday** - 靠近当前日期的日期将返回为今天、明天或昨天。

  • **naturaltime** - 此过滤器返回自特定时间以来经过多少分钟、秒或小时的字符串表示形式。例如:2001年4月6日12:57:34 变为 now,2001年4月6日12:57:04 变为 30 秒前,等等。

  • **ordinal** - 此过滤器将整数转换为其序数表示形式,并将其存储为字符串数据类型。例如:4 变为 第4

为了测试这些过滤器的运行情况,我们将在一个 Django 项目中使用这些过滤器。创建一个 Django 项目和一个应用。在 Django 应用的 views.py 文件中,应编写以下代码。(此处省略 views.py 代码示例)

from django.shortcuts import render
import datetime
def homepage(request):
   current_time = datetime.datetime.now()
   context = {
      'comma': 17937,
      'word': 1800000000,
      'current_time': current_time,
      'day1': current_time - datetime.timedelta(days=1),
   }
   return render(request, 'test.html', context)

然后,test.html 应包含以下数据以打印输出。(此处省略 test.html 代码示例)

{% load humanize %}
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>How to Use Humanize Tags in Django</title>
</head>
<body>
   <h2><u>Template Filters to Humanize Data</u></h2>
   <h3>1) intcomma</h3>
   <p>{{ comma }} translates to {{ comma | intcomma }}</p>
   <hr>
   <h3>2) intword</h3>
   <p>{{ word }} translates to {{ word | intword }}</p>
   <hr>
   <h3>3) naturalday</h3>
   <b>Current time is: {{ current_time }}</b>
   <p>{{ day1 }} translates to {{ day | naturalday }}</p>
   <hr>
</body>
</html>

获得的输出将采用以下形式 - (此处省略输出示例)

Template Filters to Humanize Data
1)intcommma
17937 translates to 17.939
2)intword
1800000000 translates to 1.8 billion
3)naturalday
Current time is April 19th 2022, 3:43pm
April 18th 2022, 3:43 pm translates to yesterday.

通过这种方式,我们可以将过滤器添加到 Django 项目中的模板中以人性化数据。这对于帮助用户理解货币兑换或时间变化特别有用。

更新于:2022年9月5日

2K+ 浏览量

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.