如何部分显示来自 django 数据库的信息?

时间:2021-07-10 14:28:14

标签: python django web django-rest-framework

我想部分显示来自 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()

这不起作用

1 个答案:

答案 0 :(得分:0)

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

您请求的输出字符串少了 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 被用作解决方案的基础