我有工作的解决方案,但我担心我的解决方案不是太python。所以我希望有人能提出一个更好的方法。
在Django版本1.8.2中,我使用的是Django -registration-redux版本1.2。我有我自己的表单,所以我设置了REGISTRATION_FORM = 'login_app.forms.MyRegForm'
另外,我需要一个功能,使只有白名单的电子邮件被允许注册。根据registration/backends/default/urls.py
寄存器视图由registration/backends/default/views.py
中的RegistrationView
类处理:
...
from registration.backends.default.views import RegistrationView
...
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
...
RegistrationView
类可以在Github上查看。因为这个类和它的函数提供了所需的功能,我已经子类化了它,并复制了它的所有内容,只添加了几行代码。在我的login_app.views.py
:
from registration.backends.default.views import RegistrationView
# and many other imports to satisfy actions inside MyRegView
class MyRegView(RegistrationView):
# some copied code
def register(self, request, form):
# some copied code
WHITELISTED_EMAILS = getattr(settings, 'WHITELISTED_EMAILS')
email_to_check = form.cleaned_data['email']
if email_to_check in WHITELISTED_EMAILS:
# registration performed
# by using copied code
else:
raise PermissionDenied
def registration_allowed(self, request):
# remaining copied code
最后我重写了url以便使用正确的视图:
...
from login_app.views import MyRegView
urlpatterns = [
...
url(r'^accounts/register/', MyRegView.as_view(), name='registration_register'),
...
]
这个解决方案很好,但是我复制了太多的代码。实现白名单的更优雅的解决方案是什么?
我认为最简单的解决方案是在您的注册表单中添加clean_email
方法,并在那里做白名单。
class MyRegForm(ParentForm):
def clean_email(self):
email = self.cleaned_data['email']
# If the parent class already cleans the email, you might want to do
# email = super(MyRegForm, self).clean_email()
# Then check email here, and raise forms.ValidationError()
# if the email is not in the whitelist
return email