django.core.exceptions.配置不正确:导入表单类时出错 pages.custom_sign_up_form:"cannot import name 'BaseSignupForm



我正在尝试扩展django allauth的SignupForm来自定义我的注册表单。需要是因为我想检查提交的电子邮件是否被接受注册,并且是通过检查管理员是否接受该电子邮件的邀请来完成的。

我没有用 forms.py 定义我的形式,而是使用了另一个名字"custom_sign_up_form.py"。下面是我导入的完整代码。

settings.py

ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm'

custom_sign_up_form.py

from allauth.account.adapter import DefaultAccountAdapter, get_adapter
from allauth.account.forms import SignupForm
from allauth.account import app_settings
# from django import forms
from invitation.models import Invitation
class CustomSignupForm(SignupForm):
errors = {
'not_invited': "Sorry! You are not yet invited.",
}
def __init__(self, *args, **kwargs):
super(CustomSignupForm, self).__init__(*args, **kwargs)
def clean(self):
super(CustomSignupForm, self).clean()
email = self.cleaned_data.get('email')
email = get_adapter().clean_email(email)
if email and app_settings.UNIQUE_EMAIL:
email = self.validate_unique_email(email)
try:
Invitation.objects.get(email=email, request_approved=True)
except Invitation.DoesNotExist:
# raise forms.ValidationError(errors['Sorry! you are not yet invited'])
self.add_error('email','Sorry! You are not yet invited')
return email

ACCOUNT_SIGNUP_FORM_CLASS是SignupForm (BaseSignupForm)的父类...

https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py#L197

如果要更改表单验证逻辑,则需要使用ACCOUNT_ADAPTER

# project/settings.py:
ACCOUNT_ADAPTER = 'project.users.adapter.MyAccountAdapter'
# project/users/adapter.py:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter
class MyAccountAdapter(DefaultAccountAdapter):
def clean_email(self, email):
"""
Validates an email value. You can hook into this if you want to
(dynamically) restrict what email addresses can be chosen.
"""
try:
Invitation.objects.get(email=email, request_approved=True)
except Invitation.DoesNotExist:
raise forms.ValidationError('Sorry! you are not yet invited')
return email

另请参阅 https://stackoverflow.com/a/23328414/7724457

最新更新