You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django-Allauth未调用自定义注册表单问题求助

Django-Allauth搭配React时自定义SignupForm不生效,name字段无法保存

我使用Django-Allauth搭配React作为前端,给自定义用户模型添加了name字段,在forms.py中重写了SignupForm以保存该字段,同时按照文档要求在settings.py中配置了:

ACCOUNT_FORMS = {'signup': 'XXXX.forms.CustomSignupForm'}

但注册时自定义表单并未初始化(添加的打印语句无输出),用户虽能创建,但未保存新增的name字段,且前端已正确发送请求体。

forms.py代码

class CustomUserCreationForm(UserCreationForm):
    name = forms.CharField(max_length=30, required=True, help_text='Enter your name.')

    class Meta:
        model = CustomUser
        fields = ("email", "name")


class CustomSignupForm(SignupForm):
    name = forms.CharField(max_length=40, required=True, help_text='Enter your name.')
    
    def __init__(self, *args, **kwargs):
        print("CustomSignupForm is being initialized")
        super().__init__(*args, **kwargs)
        
    def save(self, request):
        print("im working")
        user = super().save(request)
        user.name = self.cleaned_data['name']
        user.save()
        return user 

urls.py配置

urlpatterns = [
    path("admin/", admin.site.urls),
    path('', include('XXXX.urls')),
    path('accounts/', include('allauth.urls')),
    path("_allauth/", include("allauth.headless.urls")),
]

尝试过的解决方法

  • 尝试在settings中配置ACCOUNT_ADAPTER,adapters.py代码如下:
class CustomAccountAdapter(DefaultAccountAdapter):
#     def get_signup_form_class(self):
#         return CustomSignupForm

但仍未调用自定义表单。

  • 修改过CustomUserManager,但认为表单处理在管理器之前,因此无效果。

翻遍文档都没找到解决方案,恳请帮助!

补充settings.py配置

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent


SECRET_KEY = "XXX"

DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1','localhost']
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]
CSRF_TRUSTED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000"
]
CORS_ALLOW_CREDENTIALS = True

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    "myapp",
    'rest_framework',
    'corsheaders',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.google',
]

SITE_ID = 1

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    "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",
    "allauth.account.middleware.AccountMiddleware",
]

ROOT_URLCONF = "project.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",
                'django.template.context_processors.request',
            ],
        },
    },
]


WSGI_APPLICATION = "project.wsgi.application"


DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}


AUTH_USER_MODEL = "myapp.CustomUser"


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",},
]

AUTHENTICATION_BACKENDS = [

    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by email
    'allauth.account.auth_backends.AuthenticationBackend',

]

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': '123',
            'secret': '456',
            'key': ''
        }
    }
}


LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


STATIC_URL = "static/"


DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

ACCOUNT_EMAIL_VERIFICATION = "optional"  # or "optional"
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = False
ACCOUNT_LOGIN_BY_CODE_ENABLED = True

ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_FORMS = {'signup': 'app.forms.CustomSignupForm'}


HEADLESS_FRONTEND_URLS = {
   "account_confirm_email": "https://app.project.org/account/verify-email/{key}",

    "account_reset_password": "https://app.project.org/account/password/reset",
    "account_reset_password_from_key": "https://app.project.org/account/password/reset/key/{key}",
    "account_signup": "https://app.project.org/account/signup",

    "socialaccount_login_error": "https://app.project.org/account/provider/callback",
}

内容的提问来源于stack exchange,提问作者orchamo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:05:55