我试图在Django中创建一个自定义用户模型,但是它给了我很多错误

2024-04-19 02:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个Django项目,所以我有了调度应用程序,应用程序上的真正功能,我创建了一个“帐户”应用程序来修改基本用户模型,这样我就可以让用户用他的/她的电子邮件登录。如果你能帮我解决这个问题,我会非常感激,因为我有点困了。 但是,现在我修改了型号.py(在“帐户”应用程序中)并修改设置.py在主网站文件夹中,我收到以下错误(最后一个错误包括安装的应用程序设置错误,我不明白):

Traceback (most recent call last): File "C:/PythonProjects/tutorTrip/manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 70, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 56, in getattr self._setup(name) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 120, in init raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be a list or a tuple.

Process finished with exit code 1

遵循我的代码:

(账户)/型号.py)地址:

from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser, BaseUserManager 
)
   class UserManager(BaseUserManager):
       def create_user(self, email, password=None, active=True, 
is_staff=False, is_admin=False):
        if not email:
            raise ValueError("User must have an email")
       if not password:
            raise ValueError("Users must have a password")

        user = self.model(
            email=self.normalize_email(email),
        )
        user.set_password(password)  # change user password
        user.staff = is_staff
        user.admin = is_admin
       # user.active = is_active
       user.save(using=self._db)
       return user

def create_staffuser(self, email, password):
    # """
    # Creates and saves a staff user with the given email and password.
    # """
    user = self.create_user(
        email,
        password=password,
    )
    user.staff = True
    user.save(using=self._db)
    return user

def create_superuser(self, email, password):
    # """
    # Creates and saves a superuser with the given email and password.
    # """
    user = self.create_user(
        email,
        password=password,
    )
    user.staff = True
    user.admin = True
    user.save(using=self._db)
    return user


# user class
class User(AbstractBaseUser):
    email = models.EmailField(
        max_length=255,
        unique=True,
        verbose_name='email address',
    )
    active = models.BooleanField(default=True)  # can login
    staff = models.BooleanField(default=False)
    admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    objects = UserManager()

    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

def get_full_name(self):
    return self.email

def get_short_name(self):
    return self.email

def has_module_perms(self, app_label):
    # "Does the user have permissions to view the app `app_label`?"
    # Simplest possible answer: Yes, always
    return True

def has_perm(self, perm, obj=None):
    # "Does the user have a specific permission?"
    # Simplest possible answer: Yes, always
    return True

@property
def is_staff(self):
    return self.staff

@property
def is_admin(self):
    return self.admin

@property
def is_active(self):
    return self.active


class Profile(models.Model):
#user = models.OneToOneField(User)
# extend extra user data

(网站)/设置.py)你知道吗

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))




# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

AUTH_USER_MODEL = 'accounts.User'
# Application definition

INSTALLED_APPS = {
    'accounts.apps.AccountsConfig',
    'scheduling.apps.SchedulingConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tutorTrip.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
   },
]

WSGI_APPLICATION = 'tutorTrip.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME':     'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME':     'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'

如果你需要任何额外的代码,请告诉我。 (也许不要考虑缩进,因为我在复制到这里的代码框时遇到了一些问题,其中一些可能会显示错误。)


Tags: djangoinpyselftruereturnemaildef
1条回答
网友
1楼 · 发布于 2024-04-19 02:18:20

Django DOC - ^{}

A list of strings designating all applications that are enabled in this Django installation. Which says

但是,您将INSTALLED_APPS定义为对象({})。{}语法用于表示集合对象

因此,将INSTALLED_APPS更改为如下所示

INSTALLED_APPS = [
    ..... # your apps
      ]



示例

In [1]: a = {1,3}

In [2]: b= [1,3]

In [3]: c = (1,3)

In [4]: type(a)
Out[4]: set

In [5]: type(b)
Out[5]: list

In [6]: type(c)
Out[6]: tuple

相关问题 更多 >