问题
I'm a Django newbie.
I'd like to restrict user to use a specific domain (e.g. @gmail.com ) to sign up my Django website, but how to customize the EmailField in my registration form to do that?
FYI, here's my codes.
forms.py
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label = (u'Email Adress'))
class Meta:
model = UserProfile
exclude = ('user',)
register.html
{% extends "base.html" %}
{% block content %}
<form action = "" method ="post">
{% csrf_token%}
{% if form.errors %} <p>Please correct the following fields</p> {% endif %}
<div class ="register_div">
{% if form.username.errors %}<p class="error">{{ form.username.errors }}</p>{% endif %}
<p><label for="username"{% if form.username.errors %} class="error"{% endif %}>Username:</label></p>
<p>{{ form.username }}</p>
</div>
<div class ="register_div">
{% if form.email.errors %}<p class = "error">{{ form.email.errors }}</p>{% endif %}
<p><label for ="email"{% if form.email.errors %} class="error"{% endif %}>Email:<label><p>
<p>{{ form.email }}</p>
</div>
<p><input type="submit" alt="register" /></p>
</form>
{% endblock %}
回答1:
You can write your own clean functions for the form:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label = (u'Email Adress'))
def clean_email(self):
data = self.cleaned_data['email']
if "@gmail.com" not in data: # any check you need
raise forms.ValidationError("Must be a gmail address")
return data
class Meta:
model = UserProfile
exclude = ('user',)
More at: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
回答2:
You can achieve the same via HTML5 input tag attribute (pattern). Say for example your domain is foo.com, then the code will be:
<input id="email" type="email" pattern="[a-z.]*[@]\bfoo.com" required>
Also you can change the error message by using the setCustomValidity of the DOM element.
document.getElementById('email').setCustomValidity("Please use an @foo.com email address.");
来源:https://stackoverflow.com/questions/13240032/restrict-user-to-use-a-specific-domain-to-sign-up-django