很长时间以来,我一直无法找到上述错误的解决方案。我看了几个其他类似的问题,但无法弄清楚。如果有人能指出正确的方向,我将非常感激。 确切的错误如下:
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.
这是我的代码:
settings.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)
applications / users / 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"),
]
applications / users / 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)
applications / users / 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 = []
applications / users / 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在根目录中检测到一个未在INSTALLED_APP中注册的名为“用户”的应用。因此,当我在INSTALLED_APP中添加“用户”并删除“ applications.users.apps.CustomUsersConfig”时,Django随后会在“应用程序/用户”中检测该模型。但是,我在项目根目录中没有“用户”应用。
任何帮助或线索,将不胜感激。
答案 0 :(得分:0)
我在用户应用旁边的另一个应用进行了类似的设置,从而收到此错误。我将用户模型导入:
from users.model import User
并通过以下操作对其进行修复:
from applications.users.model import User