Login

EmailListField for Django

Author:
sciyoshi
Posted:
August 8, 2009
Language:
Python
Version:
1.1
Score:
4 (after 4 ratings)

A simple Django form field which validates a list of emails.

See this at my blog

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from email.utils import getaddresses, formataddr

from django import forms
from django.utils.translation import ugettext_lazy as _

class EmailListField(forms.CharField):
	"""
	A Django form field which validates a list of email addresses.
	
	>>> EmailListField().clean('user1@example.com')
	[u'user1@example.com']
	
	>>> EmailListField().clean('User 1 <user1@example.com>, User 2 <user2@example.com>')
	[u'User 1 <user1@example.com>', u'User 2 <user2@example.com>']
	
	>>> EmailListField().clean('invalid email address')
	Traceback (most recent call last):
	  File "<console>", line 1, in <module>
	  File "/home/sciyoshi/chideit/apps/chide/common/mail/forms.py", line 21, in clean
		raise forms.ValidationError(self.error_messages['invalid'])
	ValidationError: [u'Please enter a valid list of e-mail addresses.']
	
	>>> EmailListField().clean('"User 3>" <  "Abc\@def"@example.com  >, User 2 <$A12345@example.com >  , 3rd guy <!def!xyz%abc@example.com >')
	[u'"User 3>" <"Abc@def"@example.com>', u'User 2 <$A12345@example.com>', u'3rd guy <!def!xyz%abc@example.com>']
	"""
	default_error_messages = {
		'invalid': _('Please enter a valid list of e-mail addresses.')
	}

	def clean(self, value):
		value = super(EmailListField, self).clean(value)

		field = forms.EmailField()

		try:
			return [
				formataddr((name, field.clean(addr)))
			for name, addr in getaddresses([value])]
		except forms.ValidationError:
			raise forms.ValidationError(self.error_messages['invalid'])

More like this

  1. Mask sensitive data from logger by agusmakmun 2 weeks, 3 days ago
  2. Template tag - list punctuation for a list of items by shapiromatron 1 year, 2 months ago
  3. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 3 months ago
  4. Serializer factory with Django Rest Framework by julio 1 year, 9 months ago
  5. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 10 months ago

Comments

Please login first before commenting.