Django - Allauth 不使用自定义注册表单

问题描述 投票:0回答:1

我作为 FE 使用 Django-Allauth 和 React。我为我创建的自定义用户添加了一个名为 name for 的参数,我覆盖了 Forms.py 中的 SignupForm 来保存它,就像文档所说的那样,我将 settings.py 更改为具有

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

但是注册时表格并未启动 - 我添加了未通过的打印件。 正在创建用户 - 但可能使用默认表单,并且不添加我添加的附加参数。我检查了一下,前端正确发送了有效负载。

我在 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 

url.py

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

我还尝试在设置中使用 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",
}
django django-allauth
1个回答
0
投票

要记住的重要一点是,不存在一对一的 有头表单到无头输入有效负载的映射。例如,虽然必须 输入密码两次在头脑清醒的环境中有意义,但毫无意义 从API的角度来看。 结果,可以覆盖的头形式 通过

ACCOUNT_FORMS
在无头环境中不起作用。

不要通过

ACCOUNT_FORMS
覆盖完整的注册表单,而是提供
ACCOUNT_SIGNUP_FORM_CLASS
源自
forms.Form
并且仅列出 您需要的其他字段。这些字段将自动显示在 抬头注册表单,并将有效负载发布到时自动验证 注册端点。

© www.soinside.com 2019 - 2024. All rights reserved.