获取方法模型 returns clean_<fieldname> 方法中的空 QuerySet 对象

Get method model returns empty QuerySet object in clean_<fieldname> methods

我有一个问题。我有一个自定义用户模型,我创建了一个用于用户创建的表单。用户模型和注册表代码将在上面。在每个字段的干净方法中,用户方法不起作用。所以我想获取用户模型对象,但用户模型 return 是空的 QuerySet。但是我的数据库中有 2 个用户。我尝试在 clean_email 和 clean_username 中获取用户对象,但两种获取方法 return 都是空的 QuerySet。谁能帮我?
用户模型:

class UserManager(BaseUserManager):
    def create_user(self, email, username, first_name, last_name, date_of_birth, password=None):
        if not email:
            raise ValueError("Users must have email")
        if not username:
            raise ValueError("Users must have username")
        if not first_name:
            raise ValueError("Users must have first name")
        if not last_name:
            raise ValueError("Users must have last name")
        if not date_of_birth:
            raise ValueError("Users must have date of birth")


        email = self.normalize_email(email)
        first_name      = normalize_name(first_name)
        last_name       = normalize_name(last_name)


        user = self.model(
            email           = email,
            username        = username,
            first_name      = first_name,
            last_name       = last_name,
            date_of_birth   = date_of_birth
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, first_name, last_name, date_of_birth, password=None):
        user = self.create_user(
            email           = email,
            username        = username,
            first_name      = first_name,
            last_name       = last_name,
            date_of_birth   = date_of_birth,
            password        = password
        )


        user.is_admin = True
        user.is_superuser = True
        user.is_staff = True

        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    username                = models.CharField(max_length=20, unique=True, verbose_name="Username")
    email                   = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use")
    first_name              = models.CharField(max_length=20)
    last_name               = models.CharField(max_length=20)
    date_of_birth           = models.DateField(blank=False)
    date_created            = models.DateTimeField(auto_now_add=True)
    last_login              = models.DateTimeField(auto_now=True)
    profile_image           = models.ImageField(upload_to=profileImageRoot)
    profile_image_count     = models.IntegerField(default=0)
    spent_money             = models.FloatField(default=0)

    is_active               = models.BooleanField(default=True)
    is_admin                = models.BooleanField(default=False)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    is_verified             = models.BooleanField(default=False)

    objects = UserManager()


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth')

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"
    
    def is_birthday(self):
        if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0):
            return True
        else:
            return False


    def verify(self):
        self.is_verified = True

    def __str__(self):
        return self.get_full_name()

注册表单:

class UserRegisterForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('email', 'username', 'first_name', 'last_name', 'password1', 'password2', 'date_of_birth')


    email                   = forms.EmailField(
        widget=forms.EmailInput(
            attrs={

            }
        )
    )
    username                = forms.CharField(
        widget=forms.TextInput(
            attrs={

            }
        )
    )
    password1               = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                
            }
        ),
    )
    password2               = forms.CharField(
        widget=forms.PasswordInput(
            attrs={

            }
        ),
    )
    date_of_birth           = forms.DateField(
        widget=forms.DateInput(
            attrs={

            }
        )
    )


    def clean_email(self):
        email = self.cleaned_data.get('email')
        print(User.objects.all())
        print(f"Email {email}")

        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            return email

        print(user)
        raise forms.ValidationError(f"Sorry, but {email} is taken already")


    def clean_first_name(self):
        first_name = self.cleaned_data.get('first_name')
        first_name = normalize_name(first_name)
        return first_name


    def clean_last_name(self):
        last_name = self.cleaned_data.get('last_name')
        last_name = normalize_name(last_name)
        return last_name


    def clean_password1(self):
        password1 = self.cleaned_data.get('password1')
        length = len(password1)
        if length < 9 or length > 20:
            raise forms.ValidationError("Password must be between 9-20 characters...")
        else:
            return password1


    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password2 != password1:
            raise forms.ValidationError("Passwords are not same...")
        else:
            return password2


    def clean_date_of_birth(self):
        date_of_birth = self.cleaned_data.get('date_of_birth')
        today = date.today()

        ageofuser = age(birthday=date_of_birth)

        if ageofuser < 18:
            raise forms.ValidationError("Users must be older than 18 years old")
        
        else:
            return date_of_birth


    def clean(self):
        super().clean()

我找到了问题的原因。此问题与模型方法无关。我了解到,TestCase 类 创建一个新的测试数据库。所以,我现有的对象不在测试数据库中。当我调用 get()all() 方法时,它是正常的 return 空 QuerySet 对象。更多信息: