简体   繁体   English

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

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

I am facing problem testing my User model Which is defined as AUTH_USER_MODEL = "accounts.User"我在测试我的用户 model 时遇到问题,它被定义为AUTH_USER_MODEL = "accounts.User"

#settings.py
AUTH_USER_MODEL = "accounts.User"

and the accounts.models that is the code以及作为代码的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"]

When I am testing this in test_models.py using $ python -m pytest with following code in the file当我在 test_models.py 中使用$ python -m pytest在文件中使用以下代码进行测试时

from django.conf import settings


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

These are the errors on terminal这些是终端上的错误

$ 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 =========================================================================== 

As I am not very good in testing but Now Question is that, I'm testing this in a wrong way or there is problem in settings config as django is suggesting, However the code is working fine in without any error but I need to pass the tests as well.因为我在测试方面不是很好,但现在的问题是,我正在以错误的方式进行测试,或者设置配置中有问题,正如 django 所暗示的那样,但是代码工作正常,没有任何错误,但我需要通过测试也是如此。

One generally uses manage.py to run things related to Django because it does various initial setup, specific to your problem it has a line like so (a little different according to the project name):通常使用manage.py来运行与 Django 相关的东西,因为它会进行各种初始设置,具体到您的问题,它有这样一行(根据项目名称略有不同):

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

You get the error because there is no environment variable DJANGO_SETTINGS_MODULE set when you try to run your test.您收到错误是因为在您尝试运行测试时没有设置环境变量DJANGO_SETTINGS_MODULE Moving further one should be using the builtin test suite of Django to do testing in their Django projects as it provides much more convenience while testing.更进一步应该使用 Django 的内置测试套件在他们的 Django 项目中进行测试,因为它在测试时提供了更多的便利。 For more details see the documentation for Testing in Django有关更多详细信息,请参阅Django 中的测试文档

To use Django's test suite more efficiently you can change your file accounts\tests\test_models.py like so:为了更有效地使用 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")

And then run them by running the following line in your terminal / cmd:然后通过在终端/cmd 中运行以下行来运行它们:

python manage.py test

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “AUTH_USER_MODEL 指的是尚未安装的 model '%s'” % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: - “AUTH_USER_MODEL refers to model '%s' that has not been installed” % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured:请求设置 INSTALLED_APPS,但未配置设置 - raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured Django.core.exceptions.ImproperlyConfigured:AUTH_USER_MODEL指的是尚未安装的模型%s - Django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model %s that has not been installed django.core.exceptions.ImproperlyConfigured:请求设置INSTALLED_APPS,但未配置设置 - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured django.core.exceptions.ImproperlyConfigured:请求的设置DEFAULT_INDEX_TABLESPACE,但未配置设置 - django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured django.core.exceptions.ImproperlyConfigured:请求设置 USE_I18N,但未配置设置 - django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured django.core.exceptions.ImproperlyConfigured 错误:请求设置 INSTALLED_APPS,但未配置设置 - django.core.exceptions.ImproperlyConfigured error: Requested setting INSTALLED_APPS, but settings are not configured django.core.exceptions.ImproperlyConfigured:请求的设置DEFAULT_INDEX_TAB LESPACE,但未配置设置 - django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured django.core.exceptions.ImproperlyConfigured:请求设置 LOGGING_CONFIG,但未配置设置 - django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured django.core.exceptions.ImproperlyConfigured:AUTH_USER_MODEL 指的是尚未安装的模型“User.User” - django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'User.User' that has not been installed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM