I am trying to set up an email domain whitelist for my project's registration form.
I am using django-registration .
Here is my 'register' url rule
urlpatterns = [
...
url(r'^register/$',
RegistrationView.as_view(),
{ 'form_class': EmailDomainFilterRegistrationForm },
name='registration_register'),
...
]
And here is the EmailDomainFilterRegistrationForm
class I created
from django.core.validators import EmailValidator
from registration.forms import RegistrationForm
class EmailDomainFilterRegistrationForm(RegistrationForm):
def __init__(self, *args, **kwargs):
super(EmailDomainFilterRegistrationForm, self).__init__(*args, **kwargs)
self.fields['email'].validators = [
EmailValidator(whitelist=['epita.fr', 'lrde.epita.fr']),
]
The problem is that the whitelist is not applied at all. I can register with any email I want.
What am I doing wrong?
Django version 1.9.2
Here is how to do it (the right way).
Create a subclass of registration.forms.RegistrationForm
:
class EmailDomainFilterRegistrationForm(RegistrationForm):
def clean_email(self):
submitted_data = self.cleaned_data['email']
if not ALLOWED_DOMAINS: # If we allow any domain
return submitted_data
domain = submitted_data.split('@')[1]
logger.debug(domain)
if domain not in ALLOWED_DOMAINS:
raise forms.ValidationError(
u'You must register using an email address with a valid '
'domain ({}). You can change your email address later on.'
.format(', '.join(self.allowed_domains))
)
return submitted_data
Re-use django-registration 's urls.py
from whichever django-registration backend you're using and change the registration_register
url with
url(r'^register/$',
RegistrationView.as_view(form_class=EmailDomainFilterRegistrationForm),
name='registration_register'),
RegistrationView
above depends on which of django-registration 's backends you're using. Don't import it from the top level views.py
. Import it from the applicable backend using ONE of the following statements:
from registration.backends.hmac.views import RegistrationView
from registration.backends.model_activation.views import RegistrationView
from registration.backends.simple.views import RegistrationView
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.