python - RuntimeError:模型类 users.models.User 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中
问题描述
很长一段时间以来,我都无法找到上面发布的错误的解决方案。我查看了其他几个类似的问题,但无法弄清楚。如果有人能指出我正确的方向,我真的很感激。确切的错误如下:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10473e840>
Traceback (most recent call last):
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate
app_config.ready()
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "~/@Python_project/webservice/venv/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "~/@Python_project/webservice/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "~/@Python_project/webservice/applications/users/admin.py", line 1, in <module>
from applications.users import models
File "~/@Python_project/webservice/applications/users/models.py", line 38, in <module>
class User(AbstractBaseUser, PermissionsMixin):
File "~/Desktop/@Python_project/webservice/venv/lib/python3.6/site-packages/django/db/models/base.py", line 95, in __new__
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class applications.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
这是我的代码:
请注意,我的“用户”应用程序位于 manage.py 所在的项目根目录中的“应用程序”目录下。
设置.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"imagekit_cropper",
"bootstrap4",
"bootstrap_datepicker_plus",
"applications.events.apps.EventsConfig",
"applications.users.apps.CustomUsersConfig",
]
urls.py 与 settings.py 在同一目录中
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("applications.events.urls"), name="event"),
path("accounts/", include("applications.users.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
应用程序/用户/urls.py
from django.urls import path
from applications.users import views
from django.contrib.auth import views as auth_views
app_name = "users"
urlpatterns = [
#path("login/?next=/<str:next_path>/", views.login, name="login"),
path("login/", views.login, name="login"),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("signup/", views.signup, name="signup"),
]
应用程序/用户/views.py
from django.shortcuts import render
from django.contrib import auth
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from applications.users import models
# Create your views here.
def signup(request):
#account_form = models.CustomUserCreationForm()
return render(request, "users/user_signup.html", {"account_form": account_form})
def login(request, **kwargs):
redirect_to = request.GET.get('next', "events:retrieve_eventboard")
if request.method == 'POST':
# First get the username and password supplied
email = request.POST.get('email')
password = request.POST.get('password')
# Django's built-in authentication function:
user = auth.authenticate(email=email, password=password)
# If we have a user
if user:
# Check if the account is active
if user.is_active:
# Log in the user.
auth.login(request, user)
# Send the user back to some page.
#print("Login success")
return HttpResponseRedirect(reverse(redirect_to))
else:
# If account is not active:
return HttpResponseRedirect(reverse("users:login"))
else:
#print("Someone tried to login and failed.")
#print("They used email: {} and password: {}".format(email, password))
return HttpResponseRedirect(reverse("users:login"))
else:
# Nothing has been provided for username or password.
return render(request, "users/user_login.html")
def logout(request):
auth.logout(request)
应用程序/用户/models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from datetime import datetime
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth import get_user_model
class UserAccountManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, is_staff, is_superuser):
"""
Creates and saves a User with the given username, email and password.
"""
if not email:
raise ValueError('The email address must be set')
username = email.split("@")[0]
email = self.normalize_email(email)
user = self.model(email=email, username=username, is_staff=is_staff,
is_superuser=is_superuser, date_joined=datetime.now())
user.set_password(password)
user.save(using=self._db)
#request.session.modified = True
return user
def create_user(self, email=None, password=None):
print("create_user()")
return self._create_user(email=email, password=password, is_staff=False,
is_superuser=False)
def create_superuser(self, email, password):
print("create_superuser()")
return self._create_user(email=email, password=password, is_staff=True,
is_superuser=True)
#Define a table here
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(default="", max_length=30)
#self_introduction = models.CharField(default="", max_length=280)
#watch_list = models.
#join_list =#
is_staff = models.BooleanField(default=False,
help_text='Designates whether the user is a team staff.')
is_superuser = models.BooleanField(default=False,
help_text='Designates whether the user can log into this admin site.')
date_joined = models.DateTimeField(default=None, help_text="Time when the user account is created.")
#Tell Django that this User uses UserManager instead of the default BaseUserManager
objects = UserAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
应用程序/用户/apps.py
from django.apps import AppConfig
class CustomUsersConfig(AppConfig):
name = 'applications.users'
label = "users"
我认为可能是此错误的线索的一件事是,当我将 INSTALLED_APP 中的“applications.users.apps.CustomUsersConfig”更改为“users”时,错误更改为
"RuntimeError: Model class applications.users.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS."
我认为这意味着 Django 在根目录中检测到一个名为“users”的应用程序,该应用程序未在 INSTALLED_APP 中注册。因此,当我将“用户”添加到 INSTALLED_APP 并删除“applications.users.apps.CustomUsersConfig”时,Django 会检测到“应用程序/用户”中的模型。但是,我在项目根目录中没有“用户”应用程序。
对此问题的任何帮助或线索将不胜感激。
解决方案
通过在我的用户应用程序旁边使用另一个应用程序进行类似的设置,我得到了这个错误。我导入了用户模型:
from users.model import User
并通过以下方式修复它:
from applications.users.model import User
推荐阅读
- r - 删除包含值的行后面的所有行
- java - 如何控制外设的数据速率?
- python - Python 在 json.loads 上引发 JSONDecodeError("Expecting value", s, err.value) 错误
- django - Django 获取文件地址
- node.js - 在 expressJS 路由中调用 leave 失败
- visual-studio - 如何在 Visual Studio 项目解决方案中编译复制和粘贴的文件?
- python - 使用 pandas 从写入到镶木地板
- python - 悬停在 matplotlib 节点上
- algolia - Algolia 如何在规则中添加特定条件时隐藏所有结果?
- laravel - 为 Vue v3 导入 Vue-luxon - this.$luxon 不是函数错误