错误:inside.UserProfile.user: (fields.E301) 字段定义与模型 'auth.User' 的关系,已被换出
ERRORS: inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
我是 Django 的初学者。
我正在尝试构建一个具有用户身份验证的应用程序。但是我想要额外的字段,比如国家和 phone 号码,我不想要任何用户名字段(我想要 phone 号码作为用户名),所以我建立了一个自定义用户 class.
已经有人问过同样错误的问题,但它们与我的用例不完全相关,解决方案对我不起作用。
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser
from django.conf import settings
from django_countries.fields import CountryField
# Create your models here.
class UserProfile(AbstractBaseUser):
user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
country = CountryField()
uid = models.UUIDField(
default = None,
blank = True,
null = True,
unique = True,
)
USERNAME_FIELD = "uid"
REQUIRED_FIELDS = ['phone_number', 'country']
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile
from django_countries.fields import CountryField
# Create your forms here..
class NewUserForm(UserCreationForm):
phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
country = CountryField()
class Meta:
model = UserProfile
fields = ("phone_number", "country", "password1", "password2")
def save(self, commit = True):
user = super(NewUserForm, self).save(commit = False)
user.phone_number = self.cleaned_data['phone_number']
user.username = user.phone_number
user.country = self.cleaned_data['country']
if commit:
user.save()
return user
settings.py:
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 4.0.1.
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-pu46*rr%pr(^utidu^bob6o#f*s4w5ig#$fmc$f@ga45+p2wzc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'inside.apps.InsideConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'phonenumber_field',
]
AUTH_USER_MODEL = 'inside.UserProfile'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
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 = 'app.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 = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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 = 'Asia/Kolkata'
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'
Django 抛出此错误:
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 488, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
System check identified 1 issue (0 silenced).
您正在定义与默认 User
模型的关系,您不再使用该模型,因为您已经创建了自定义用户模型。删除 one_to_one_field
以避免此错误
对于进一步的错误,您必须创建自定义 manager
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser
from django.conf import settings
from django_countries.fields import CountryField
# Create your models here.
class UserProfile(AbstractBaseUser):
# Remove this as you no longer using the default User Model.
# user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
country = CountryField()
# As you are using UID as your username field
# it is not safe to make it blank and null true
uid = models.UUIDField(
default = None,
blank = True,
null = True,
unique = True,
)
USERNAME_FIELD = "uid"
REQUIRED_FIELDS = ['phone_number', 'country']
# Create your custom user manager
objects = YOUR_CUSTOM_USER_MANAGER()
注意:由于您使用 uid 作为您的用户名字段,您必须编写一个自定义身份验证后端,以便您可以使用 phone 号码来验证用户,否则您必须使用 phone 如果您不想创建自定义身份验证后端,则将数字作为用户名字段。
我是 Django 的初学者。 我正在尝试构建一个具有用户身份验证的应用程序。但是我想要额外的字段,比如国家和 phone 号码,我不想要任何用户名字段(我想要 phone 号码作为用户名),所以我建立了一个自定义用户 class. 已经有人问过同样错误的问题,但它们与我的用例不完全相关,解决方案对我不起作用。
models.py:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser
from django.conf import settings
from django_countries.fields import CountryField
# Create your models here.
class UserProfile(AbstractBaseUser):
user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
country = CountryField()
uid = models.UUIDField(
default = None,
blank = True,
null = True,
unique = True,
)
USERNAME_FIELD = "uid"
REQUIRED_FIELDS = ['phone_number', 'country']
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import UserProfile
from django_countries.fields import CountryField
# Create your forms here..
class NewUserForm(UserCreationForm):
phone_number = forms.RegexField(max_length = 16, regex = r'^\+?1?\d{9,15}$')
country = CountryField()
class Meta:
model = UserProfile
fields = ("phone_number", "country", "password1", "password2")
def save(self, commit = True):
user = super(NewUserForm, self).save(commit = False)
user.phone_number = self.cleaned_data['phone_number']
user.username = user.phone_number
user.country = self.cleaned_data['country']
if commit:
user.save()
return user
settings.py:
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 4.0.1.
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-pu46*rr%pr(^utidu^bob6o#f*s4w5ig#$fmc$f@ga45+p2wzc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'inside.apps.InsideConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'phonenumber_field',
]
AUTH_USER_MODEL = 'inside.UserProfile'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
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 = 'app.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 = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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 = 'Asia/Kolkata'
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'
Django 抛出此错误:
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Kanav\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 488, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
inside.UserProfile.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
System check identified 1 issue (0 silenced).
您正在定义与默认 User
模型的关系,您不再使用该模型,因为您已经创建了自定义用户模型。删除 one_to_one_field
以避免此错误
对于进一步的错误,您必须创建自定义 manager
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser
from django.conf import settings
from django_countries.fields import CountryField
# Create your models here.
class UserProfile(AbstractBaseUser):
# Remove this as you no longer using the default User Model.
# user = models.OneToOneField(User, on_delete = models.DO_NOTHING)
phone_number = models.CharField(max_length = 16, unique = True, blank = False, null = False)
country = CountryField()
# As you are using UID as your username field
# it is not safe to make it blank and null true
uid = models.UUIDField(
default = None,
blank = True,
null = True,
unique = True,
)
USERNAME_FIELD = "uid"
REQUIRED_FIELDS = ['phone_number', 'country']
# Create your custom user manager
objects = YOUR_CUSTOM_USER_MANAGER()
注意:由于您使用 uid 作为您的用户名字段,您必须编写一个自定义身份验证后端,以便您可以使用 phone 号码来验证用户,否则您必须使用 phone 如果您不想创建自定义身份验证后端,则将数字作为用户名字段。