Restrict user to use a specific domain to sign up : django

前端 未结 2 647
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 08:14

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

相关标签:
2条回答
  • 2021-01-01 08:39

    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

    0 讨论(0)
  • 2021-01-01 08:55

    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.");
    
    0 讨论(0)
提交回复
热议问题