I want to replace the original User of django with my own User, but the following error occurred
there is my settings.py,I mainly addedAUTH_USER_MODEL = 'tools.User'
from datetime import timedelta
from pathlib import Path
import django
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'channels',
"daphne",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework_simplejwt',
'corsheaders',
'campus_services',
'edu_admin',
'interaction',
'tools',
]
AUTH_USER_MODEL = 'tools.User'
# Application definition
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'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 = 'backend.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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.2/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.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'SIGNING_KEY': "this is my SIGNING_KEY",
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
CORS_ORIGIN_ALLOW_ALL = True
ASGI_APPLICATION = 'backend.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
The main structure is as follows,User in models.py
├─backend
│ │ asgi.py
│ │ routing.py
│ │ settings.py
│ │ urls.py
│ │ wsgi.py
│ │ __init__.py
│
├─tools
│ │ admin.py
│ │ apps.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ ├─migrations
│ │
│ ├─models
│ │ │ models.py
│ │ │ __init__.py
│ ├─urls
│ │ │ index.py
│ │ │ __init__.py
models.py
class UserManager(BaseUserManager):
def create_user(self, email, username, password=None, **extra_fields):
if not email:
raise ValueError('email error')
if not username:
raise ValueError('username error')
user = self.model(email=email, username=username, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_staff', True)
return self.create_user(email, username, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
user_id = models.BigIntegerField(primary_key=True)
username = models.CharField(max_length=255, unique=True)
email = models.EmailField(max_length=255, unique=True)
password = models.CharField(max_length=255)
avatar = models.CharField(max_length=255, blank=True, null=True)
status = models.BigIntegerField(blank=True, null=True)
role = models.CharField(max_length=7, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def set_password(self, raw_password):
self.password = bcrypt.hashpw(raw_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
self._password = raw_password
class Meta:
db_table = 'user'
app_label = 'tools'
class UserAdmin(BaseUserAdmin):
model = User
fieldsets = (
(None, {'fields': ('email', 'username', 'password', 'avatar', 'status', 'role', 'is_active', 'is_staff')}),
('Permissions', {'fields': ('is_superuser',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'username', 'password1', 'password2', 'is_staff', 'is_active', 'is_superuser')}
),
)
list_display = ('email', 'username', 'is_staff')
search_fields = ('email', 'username')
ordering = ('email',)
and there is admin.py in tools
admin.site.register(User, UserAdmin)
if run python manage.py makemigrations
and # AUTH_USER_MODEL = 'tools.User
,it happened below,
SystemCheckError: System check identified some issues:
ERRORS:
auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'tools.User.groups'.
HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'tools.User.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'auth.User.user_permissions' clashes with reverse accessor for 'tools.User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'auth.User.user_permissions' or 'tools.User.user_permissions'.
tools.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'tools.User.groups' clashes with reverse accessor for 'auth.User.groups'.
HINT: Add or change a related_name argument to the definition for 'tools.User.groups' or 'auth.User.groups'.
tools.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'tools.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'tools.User.user_permissions' or 'auth.User.user_permissions'.
I hope you can provide me with a solution to this problem or other ways to implement my ideas. Thank you very much for your answer. If you have any other details about my project, please feel free to ask
New contributor
Liang Shu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.