【问题标题】:django.core.exceptions.ImproperlyConfigured: Requested setting AUTH_USER_MODEL, but settings are not configureddjango.core.exceptions.ImproperlyConfigured:请求设置 AUTH_USER_MODEL,但未配置设置
【发布时间】:2021-08-07 11:31:27
【问题描述】:

我在测试定义为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 所暗示的那样,设置配置中存在问题,但是代码工作正常,没有任何错误,但我也需要通过测试。

【问题讨论】:

  • 你在 settings.py 中设置了AUTH_USER_MODEL 吗?
  • 在 settings.py 中是 AUTH_USER_MODEL = "accounts.User"

标签: python django unit-testing pytest


【解决方案1】:

通常使用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

【讨论】:

  • 感谢@Abdul Aziz Barkat 的回答
猜你喜欢
  • 2018-05-21
  • 2020-04-12
  • 2015-04-16
  • 1970-01-01
  • 2020-08-25
  • 2021-10-04
  • 2014-07-23
  • 2020-09-27
  • 2017-10-21
相关资源
最近更新 更多