在 django 中使用信号,尝试生成用于短信验证的代码,但生成的代码在管理员中不可见。我错过了什么?

Using signals in django, trying to generate code for SMS verification but generated code is not visible in admin. what am i missing?

文件夹结构 enter image description here

models.py 来自 face_detect

from django.db import models
from django.contrib.auth.models import User


# Create your models here.
class Profile(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    mobile = models.CharField(max_length=10,null=True)
    add = models.CharField(max_length=10,null=True)
    image = models.FileField(null=True)

    def __str__(self):
        return self.user.username

models.py 来自 otp

from django.db import models
from django.contrib.auth.models import User
from face_detect.models import Profile
import random
# Create your models here.

class Code(models.Model):
    number = models.CharField(max_length=5, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.number)

    #otp verification
    def save(self, *args, **kwargs):
        number_list = [x for x in range(10)]
        code_items = []

        for i in range(5):
            num = random.choice(number_list)
            code_items.append(num)

        code_string = "".join(str(item) for item in code_items)
        self.mobile = code_string

        super().save(*args,**kwargs)

signals.py 来自 otp

from face_detect.models import Profile
from django.contrib.auth.models import User
from .models import Code
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def post_save_generate_code(sender, instance, created, *args, **kwargs):
    if created:
        Code.objects.create(user=instance)

apps.py 来自 otp

from django.apps import AppConfig


class OtpConfig(AppConfig):
    name = 'otp'

    def ready(self):
        import otp.signals

init.py 来自 otp

default_app_config = 'otp.apps.OtpConfig'

admin.py 来自 otp

from django.contrib import admin
from .models import Code
# Register your models here.
admin.site.register(Code)

http://127.0.0.1:8000/admin/otp/code/ 中看到的代码 enter image description here

代码不可见。

如何使代码可见,以便在登录时使用它进行 otp 验证。

提前致谢

在管理页面你会看到 __str__ 方法,所以你的代码似乎没有问题很可能你的代码实例的值是“”,还有一件事

def __str__(self):
    return str(self.number)

你不需要将它转换为 str 这里它已经是 char 字段 还有一件事在这里:

   def __str__(self):
        return self.user.username

Profile 模型中,您使用户可为空,因此这意味着并非所有配置文件实例都可能没有用户,因此您将得到 NoneType has no attribute username 将其更改为此以防止出现此错误:

def __str__(self):
        return self.user.username if self.user else ""