Skip to content

Instantly share code, notes, and snippets.

@diogosimao
Forked from dokterbob/fields.py
Created October 4, 2018 02:28
Show Gist options
  • Save diogosimao/ba82634b5669dcd6fdb54f514f515bc1 to your computer and use it in GitHub Desktop.
Save diogosimao/ba82634b5669dcd6fdb54f514f515bc1 to your computer and use it in GitHub Desktop.
Email field with domain existence validation for Django.
import logging
logger = logging.getLogger(__name__)
# Note: we need dnspython for this to work
# Install with `pip install dnspython`
import dns.resolver, dns.exception
from django import forms
from django.utils.translation import ugettext as _
class ValidatingEmailField(forms.EmailField):
"""
Django EmailField which checks for MX records on the email domain.
Requires dnspython to be installed.
"""
def clean(self, value):
email = super(ValidatingEmailField, self).clean(value)
domain = email.split('@')[1]
# Make sure the domain exists
try:
logger.debug('Checking domain %s', domain)
results = dns.resolver.query(domain, 'MX')
except dns.exception.DNSException, e:
logger.debug('Domain %s does not exist.', e)
raise \
forms.ValidationError(_(u"The domain %s could not be found.")
% domain)
return email
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment