python - RuntimeError : Model class users. models.User 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中

标签 python django

我很长时间都无法找到上面发布的错误的解决方案。我查看了其他几个类似的问题,但无法弄清楚。如果有人能指出我正确的方向,我真的很感激。 具体错误如下:

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.

这是我的代码:

请注意,我的“users”应用程序位于“applications”目录下,该目录位于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)

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 在根目录中检测到一个名为“users”的应用程序,该应用程序未在 INSTALLED_APP 中注册。因此,当我将“users”添加到 INSTALLED_APP 并删除“applications.users.apps.CustomUsersConfig”时,Django 会检测“applications/users”中的模型。但是,我的项目根目录中没有“users”应用程序。

对此问题的任何帮助或线索将不胜感激。

最佳答案

我通过与我的用户应用程序旁边的另一个应用程序进行类似的设置而出现此错误。我导入了 User 模型:

from users.model import User

并通过以下操作修复它:

from applications.users.model import User

关于python - RuntimeError : Model class users. models.User 未声明显式 app_label 并且不在 INSTALLED_APPS 中的应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53780148/

相关文章:

python - 在 pandas groupby 中提取一系列相同数字中的第一个数字

python - 为什么FormSet在django2中只保存一个表单的数据

python - win32com 有 python3 版本吗?

python - 对完整字符串数据帧进行一次热编码

python - 在 django 1.5 中以一种形式使用两个模型

python - 如何在 django 1.9 中获取用户个人资料

django - 具有多个 django 站点的 celery

Python 的 argparse : How to use keyword as argument's name

python - 从一组问题中随机选择

django - 在 django : the last post of each user 中过滤