我在自定义allauth注册模块时遇到了麻烦,在这里我无法摆脱“用户名”字段。我确实在settings.py文件中采取了所有必需的措施来覆盖它,例如:
"""
Django settings for mackta project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f!0kitfww9lbpk+5uppbq)#an(#poh*t9is3&$=#8o!*a#y5e&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'mackta_api',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'rest_auth.registration',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
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 = 'mackta.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 = 'mackta.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'mackta_api.UserProfile'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER' : 'mackta_api.api.serializers.CustomRegisterSerializer'
}
SITE_ID = 1
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
# USERNAME_FIELD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
我确实实现了REST_AUTH_REGISTER_SERIALIZERS来指定我愿意用于注册的字段。
settings.py
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER' : 'mackta_api.api.serializers.CustomRegisterSerializer'
}
SITE_ID = 1
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
# USERNAME_FIELD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
serializers.py
class CustomRegisterSerializer(RegisterSerializer):
first_name = serializers.CharField(required=True, max_length=100,)
last_name = serializers.CharField(required=True, max_length=100)
email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED)
password = serializers.CharField(required=True, write_only=True)
def get_cleaned_data(self):
super(CustomRegisterSerializer, self).get_cleaned_data()
return {
'first_name' : self.validated_data.get('first_name', ''),
'last_name' : self.validated_data.get('last_name', ''),
'email' : self.validated_data.get('email', ''),
'password' : self.validated_data.get('password', '')
}
models.py
class UserProfileManager(BaseUserManager):
# """userprofile """
def create_user(self, email, first_name, last_name, password=None):
# """userprofile instance """
if not email:
raise ValueError('Invalid e-mail address')
email = self.normalize_email(email)
user = self.model(email=email, first_name=first_name, last_name=last_name)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, first_name, last_name, password):
# """creating superuser instance"""
user = self.create_user(email, first_name, last_name, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class UserProfile(AbstractBaseUser, PermissionsMixin):
# """db model for users in the system"""
# user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField(max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
user_name = None
objects = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
"""retreive full name of user"""
return f"{self.first_name} {self.last_name}"
def get_short_name(self):
"""retreive short name of user"""
return self.first_name
def __str__(self):
"""return string representation of our user"""
return self.first_name