django.core.exceptions.ImproperlyConfigured: 请求设置 AUTH_USER_MODEL,但未配置设置

django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured

我在测试定义为 AUTH_USER_MODEL = "accounts.User"

的用户模型时遇到问题
#settings.py
AUTH_USER_MODEL = "accounts.User"

accounts.models即代码

import os

from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import UnicodeUsernameValidator
from django.core.validators import MinLengthValidator
from django.db import models
from django.utils.translation import gettext_lazy as _


class Avatar(models.Model):
    photo = models.ImageField(upload_to="avatars")

    def __str__(self):
        return os.path.basename(self.photo.name)


class User(AbstractUser):
    username = models.CharField(
        _("username"),
        max_length=150,
        unique=True,
        help_text=_(
            "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only."
        ),
        validators=[UnicodeUsernameValidator(), MinLengthValidator(3)],
        error_messages={"unique": _("A user with that username already exists."),},
    )
    avatar = models.ForeignKey(
        "Avatar", null=True, blank=True, on_delete=models.PROTECT
    )
    is_guest = models.BooleanField(default=False)

    class Meta:
        ordering = ["-id"]

当我在 test_models.py 中使用 $ python -m pytest 和文件中的以下代码进行测试时

from django.conf import settings


def test_custom_user_model():
    assert settings.AUTH_USER_MODEL == "accounts.User"

这些是终端上的错误

$ python -m pytest
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.1, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: C:\ProjectCode\Main-Project\Django-REST-Framework-React-BoilerPlate
plugins: cov-2.11.1, django-4.2.0
collected 1 item

accounts\tests\test_models.py F                                                                                                                                   [100%]

=============================================================================== FAILURES =============================================================================== 
________________________________________________________________________ test_custom_user_model ________________________________________________________________________ 

    def test_custom_user_model():
>       assert settings.AUTH_USER_MODEL == "accounts.User"

accounts\tests\test_models.py:5:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _  
venv\lib\site-packages\django\conf\__init__.py:82: in __getattr__
    self._setup(name)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _  

self = <LazySettings [Unevaluated]>, name = 'AUTH_USER_MODEL'

    def _setup(self, name=None):
        """
        Load the settings module pointed to by the environment variable. This
        is used the first time settings are needed, if the user hasn't
        configured settings manually.
        """
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ("setting %s" % name) if name else "settings"
>           raise ImproperlyConfigured(
                "Requested %s, but settings are not configured. "
                "You must either define the environment variable %s "
                "or call settings.configure() before accessing settings."
                % (desc, ENVIRONMENT_VARIABLE))
E           django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

venv\lib\site-packages\django\conf\__init__.py:63: ImproperlyConfigured
======================================================================= short test summary info ======================================================================== 
FAILED accounts/tests/test_models.py::test_custom_user_model - django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not co...
========================================================================== 1 failed in 0.61s =========================================================================== 

因为我不太擅长测试,但现在的问题是,我正在以错误的方式测试它,或者 django 建议的设置配置中存在问题,但是代码运行良好,没有任何错误但我也需要通过测试。

一个人通常使用 manage.py 到 运行 与 Django 相关的东西,因为它会进行各种初始设置,具体到你的问题它有这样一行(根据项目名称略有不同) :

os.environ.setdefault('DJANGO_SETTINGS_MODULE', '<PROJECT_NAME_HERE>.settings')

您收到错误是因为当您尝试 运行 测试时没有设置环境变量 DJANGO_SETTINGS_MODULE。更进一步应该使用 Django 的内置测试套件在他们的 Django 项目中进行测试,因为它在测试时提供了更多的便利。有关详细信息,请参阅 Testing in Django

的文档

要更有效地使用 Django 的测试套件,您可以像这样更改文件 accounts\tests\test_models.py

from django.test import TestCase
from django.conf import settings


class SettingsTestCase(TestCase):
    def test_custom_user_model(self):
        self.assertEqual(settings.AUTH_USER_MODEL, "accounts.User")

然后 运行 通过 运行 在您的终端/cmd 中输入以下行:

python manage.py test