TypeError:ForeignKey(['app_label.model_name']) is invalid.First parameter to ForeignKey must be either a model, a model name, or the string 'self'
TypeError:ForeignKey(['app_label.model_name']) is invalid.First parameter to ForeignKey must be either a model, a model name, or the string 'self'
我正在尝试在 Django 中创建自定义模型。但是当尝试迁移时,我收到错误消息:
TypeError: ForeignKey(['custom_models.CustomUser']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
我已经尝试了所有方法,大部分答案都与外键有关,但我没有在模型中使用任何外键关系,这里是我的代码:
models.py :
from django.db import models
from django.contrib.auth.models import AbstractBaseUser , BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self , email , username , password=None):
if not email:
raise ValueError('this is not correct email.')
if not username:
raise ValueError('this is not correct username.')
user = self.model(
email = self.normalize_email(email),
usename = username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self , email , username , password ):
user = self.create_user(
email = self.normalize_email(email),
username = username,
password = password
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.is_active=True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=60 )
email = models.EmailField(max_length=60 , verbose_name='email' , unique=True)
date_joined = models.DateTimeField(auto_now=True , verbose_name='date joined')
last_login = models.DateTimeField(auto_now=True , verbose_name='last login')
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=True)
is_active = models.BooleanField(default=False)
is_superuser= models.BooleanField(default=False)
hide_mail= models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = 'username'
objects = CustomUserManager()
def __str__(self):
return self.username
def has_perm(self , perm , obj=None):
return self.is_admin
def has_module_permission(self , app_label):
return True
这是 settings.py
"""
Django settings for custom_models project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=hipnv(5-ogef&#e0fwmd+ng-**gf2i1(-j#&_0p03jk8$gbg8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = [ 'custom_models.CustomUser' ]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core.custom_models' ,
]
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 = 'custom_models.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 = 'custom_models.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
我之前也在 settings.py 中尝试过这个:
AUTH_USER_MODEL = 'custom_models.CustomUser'
但我得到了:
SystemCheckError: System check identified some issues:
ERRORS:
custom_models.CustomUser: (auth.E001) 'REQUIRED_FIELDS' must be a list or tuple.
我已经尝试了网上的所有方法,请帮助我解决问题。
你的答案在错误消息中是正确的'REQUIRED_FIELDS' must be a list or tuple.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]
我正在尝试在 Django 中创建自定义模型。但是当尝试迁移时,我收到错误消息:
TypeError: ForeignKey(['custom_models.CustomUser']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
我已经尝试了所有方法,大部分答案都与外键有关,但我没有在模型中使用任何外键关系,这里是我的代码:
models.py :
from django.db import models
from django.contrib.auth.models import AbstractBaseUser , BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self , email , username , password=None):
if not email:
raise ValueError('this is not correct email.')
if not username:
raise ValueError('this is not correct username.')
user = self.model(
email = self.normalize_email(email),
usename = username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self , email , username , password ):
user = self.create_user(
email = self.normalize_email(email),
username = username,
password = password
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.is_active=True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser):
username = models.CharField(max_length=60 )
email = models.EmailField(max_length=60 , verbose_name='email' , unique=True)
date_joined = models.DateTimeField(auto_now=True , verbose_name='date joined')
last_login = models.DateTimeField(auto_now=True , verbose_name='last login')
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=True)
is_active = models.BooleanField(default=False)
is_superuser= models.BooleanField(default=False)
hide_mail= models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = 'username'
objects = CustomUserManager()
def __str__(self):
return self.username
def has_perm(self , perm , obj=None):
return self.is_admin
def has_module_permission(self , app_label):
return True
这是 settings.py
"""
Django settings for custom_models project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=hipnv(5-ogef&#e0fwmd+ng-**gf2i1(-j#&_0p03jk8$gbg8'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
AUTH_USER_MODEL = [ 'custom_models.CustomUser' ]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core.custom_models' ,
]
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 = 'custom_models.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 = 'custom_models.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
我之前也在 settings.py 中尝试过这个:
AUTH_USER_MODEL = 'custom_models.CustomUser'
但我得到了:
SystemCheckError: System check identified some issues:
ERRORS:
custom_models.CustomUser: (auth.E001) 'REQUIRED_FIELDS' must be a list or tuple.
我已经尝试了网上的所有方法,请帮助我解决问题。
你的答案在错误消息中是正确的'REQUIRED_FIELDS' must be a list or tuple.
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username',]