I have working solution however I affraid my solution isn't much pythonic. So I hope somebody will suggest a better way.
With Django ver 1.8.2 I am using django-registration-redux ver 1.2. I have my own form therefore I have setting REGISTRATION_FORM = 'login_app.forms.MyRegForm'
.
Additionally I need a feature so that only whitelisted emails are allowed to register. According to registration/backends/default/urls.py
register view is handled by class RegistrationView
in registration/backends/default/views.py
:
...
from registration.backends.default.views import RegistrationView
...
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
...
RegistrationView
class can be viewed on Github. Because this class with it's functions provides required functionality I have subclassed it and copied all it's content only adding few lines of my code. In my 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
Finally I have overwritten url so that the right view is used:
...
from login_app.views import MyRegView
urlpatterns = [
...
url(r'^accounts/register/', MyRegView.as_view(), name='registration_register'),
...
]
This solution works fine, but I am copying too much code. What is more elegant solution for whitelist implementation?
I think the easiest solution is to add a clean_email
method to your registration form, and do the whitelisting there.
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