Ticket #18120: models_domainnamefield.txt

File models_domainnamefield.txt, 1.6 KB (added by michele, 12 years ago)
Line 
1Index: db/models/fields/__init__.py
2===================================================================
3--- db/models/fields/__init__.py (revision 17904)
4+++ db/models/fields/__init__.py (working copy)
5@@ -627,6 +627,31 @@
6 defaults.update(kwargs)
7 return super(CharField, self).formfield(**defaults)
8
9+class DomainNameField(CharField):
10+ """An Internationalized Domain Name in ASCII or UTF format, stored as idna-encoded (ASCII) string."""
11+ description = _("Internet Domain Name")
12+
13+ def __init__(self, *args, **kwargs):
14+ accept_idna = kwargs.pop('accept_idna', True)
15+ kwargs['max_length'] = 255
16+ super(CharField, self).__init__(*args, **kwargs)
17+ self.validators.append(validators.DomainNameValidator(accept_idna=accept_idna))
18+
19+ def to_python(self, value):
20+ # we always store domain names in ASCII format
21+ value = super(DomainNameField, self).to_python(value)
22+ # make sure we got called on RAW data, because django calls to_python()
23+ # even on already-python data. IDNA-encoding UTF would raise exception.
24+ if value.encode('idna') != value: # value UTF (python already)
25+ return value
26+ # value is RAW or python-ASCII, safe to encode in either case
27+ return value.encode('idna')
28+
29+ def get_prep_value(self, value):
30+ # we always store domain names in ASCII format
31+ return value.encode('idna')
32+
33+
34 # TODO: Maybe move this into contrib, because it's specialized.
35 class CommaSeparatedIntegerField(CharField):
36 default_validators = [validators.validate_comma_separated_integer_list]
Back to Top