Skip to content

Instantly share code, notes, and snippets.

@rafen
Created January 19, 2017 19:13
Show Gist options
  • Save rafen/ac62201396bb7fb0d0f7155ab2466a62 to your computer and use it in GitHub Desktop.
Save rafen/ac62201396bb7fb0d0f7155ab2466a62 to your computer and use it in GitHub Desktop.
django-full-email

Full e-mail address Field for Django

Out of the box, Django e-mail fields for both database models and forms only accept plain e-mail addresses. For example, joe@hacker.com is accepted.

On the other hand, full e-mail addresses which include a human-readable name, for example the following address fails validation in Django::

Joe Hacker <joe@hacker.com>

Base on: https://gist.github.com/akaihola/1505228

from django import forms
from django.core.validators import validate_email
from django.forms.fields import Field
from django.utils.translation import ugettext_lazy as _
class FullEmailField(Field):
description = _(u"Full email ('Full Name <email@address>')")
def clean(self, value):
try:
validate_email(value)
except forms.ValidationError:
# Trivial case failed. Try for possible Full Name <email@address>
if value and u'<' in value and value.endswith(u'>'):
parts = value.rsplit(u'<', 1)
email_part = parts[1][:-1]
validate_email(email_part)
else:
validate_email(value)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment