【问题标题】:how to partially display information from django database?如何部分显示来自 django 数据库的信息?
【发布时间】:2021-09-20 12:18:34
【问题描述】:

我想部分显示来自 django 数据库的信息。例如:

数据库中有一个电话号码 - +33547895132。 在 html 中我想显示 - +3354*****2

models.py:

class Product(models.Model):
    number = models.CharField(max_length=25)
    num = models.CharField(max_length=7, blank=True)

    def couple(self, *arg, **kwarg):
        self.num = self.number[:6]
        super().couple()

这不起作用

【问题讨论】:

  • 您是否尝试过将信息转换为字符串,编辑字符串,然后显示?一旦信息是 Python 字符串,您可以在几行中完成此操作。
  • 如何在这里发布代码?
  • 您可以编辑您的帖子并为其添加代码!

标签: python django web django-rest-framework


【解决方案1】:

如果你想返回一个与原始字符串长度相同的字符串,下面会这样做。

您请求的输出字符串少了 1 个字符。

tel = '+33547895132'

def get_masked(input: str, maxpre: int=5, maxpost: int=1, maskchr: str='*') -> str:
    """
    Returns a masked string based on the input values

            Parameters:
                    input   (str): the input string
                    maxpre  (int): how much characters from the start to show
                    maxpost (int): how much characters at the end to show
                    maskchr (str): the charcter used to mask

            Returns:
                    (str):         masked string
    """
    # check to see if we can actually mask this much
    if len(input) < maxpre + maxpost:
        return input
    else:
        fillwidth = len(input) - maxpost
        return f'{input[:maxpre]:{maskchr}<{fillwidth}}{input[fillwidth:]}'


print(get_masked(tel, maxpre=3, maxpost=2))
# this prints:
'+33*******32'


print(get_masked(tel))
# this prints:
'+3354******2'

This answer 被用作解决方案的基础

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多