如何在 API 响应中隐藏密码?

How to hide password in API response?

我知道有些人可能会说,如果我必须隐藏密码,则无需在 api-response 中提供密码。但关键是,即使我进入管理部分,我也可以看到密码哈希值,这就是我这样做的原因。

所以我的问题是,如何在 API 回复中隐藏该密码。对于前。使用星号。

注意:我的数据有一个自定义模型。 我只需要一个函数以及在哪里使用它。

models.py

from django.db import models
from django.contrib.auth.hashers import make_password


class MyUser(models.Model):
    full_name = models.CharField(max_length=128)
    profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True)
    username = models.CharField(max_length=128, unique=True)
    birth_date = models.DateField(blank=True)
    gender = models.CharField(max_length=10, blank=True)
    password = models.CharField(max_length=255)
    contact = models.CharField(max_length=15, blank=True)
    email = models.CharField(max_length=100, unique=True)
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.username

    def save(self, *args, **kwargs):
        if not self.pk:
            self.password = make_password(self.password)
        super(MyUser, self).save()

您可以提供任意数量的星号,或提供哈希密码 (user.password)。但是,您无法知道用户的密码是什么,或者其中有多少个字符,因此无法提供 ************(相同字符数)的密码。

如果您觉得需要提供一些东西,我建议您只选择任意数量的星号。

顺便说一句,我强烈建议您查看 the documentation for extending the Django User model,而不是完全自己动手。

最好覆盖 django.contrib.auth.models 中的 BaseUserManager、AbstractBaseUser 以使用您的自定义模型。因此它将充当默认的用户模型(built-in 模型)并且它将完成所有工作。 Follow this link to the guide(Code) or Follow this link for step by step brief guide(video tutorial)