This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
/
fields.py
452 lines (405 loc) · 13.9 KB
/
fields.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import datetime
from django import forms
from django.db import models, router
from django.utils import simplejson as json
from django.forms.util import from_current_timezone
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from phonenumbers import PhoneNumber
from phonenumbers.phonenumberutil import format_number, parse, PhoneNumberFormat, NumberParseException
from south.modelsinspector import add_introspection_rules
from common.utils import dumps, loads, Encoder, format_us_phone_number
class FlexibleDateTimeField(forms.DateTimeField):
"""
Extends forms.DateTimeField to accept 12-hour (AM/PM) clock times also.
"""
def to_python(self, value):
try:
result = super(FlexibleDateTimeField, self).to_python(value)
return from_current_timezone(result)
except ValidationError as e:
pass
try:
return datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
except:
pass
raise ValidationError("invalid date time, does not match any formats")
input_formats = list(forms.DateTimeField.input_formats)+[
'%Y-%m-%dT%H:%M:%SZ',
'%Y-%m-%dT%H:%M:%S',
# add in some 12-hour clock formats
'%m/%d/%Y %I:%M%p',
'%m/%d/%Y %I:%M %p',
'%m/%d/%y %I:%M%p',
'%m/%d/%y %I:%M %p',
]
class JSONWidget(forms.Textarea):
def render(self, name, value, attrs=None):
if not isinstance(value, basestring):
value = dumps(value, indent=2)
return super(JSONWidget, self).render(name, value, attrs)
class JSONFormField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs['widget'] = JSONWidget
super(JSONFormField, self).__init__(*args, **kwargs)
def clean(self, value):
if not value: return
try:
return loads(value)
except Exception, exc:
raise forms.ValidationError(u'JSON decode error: %s' % (unicode(exc),))
add_introspection_rules([], ["^common\.fields\.JSONField"])
class JSONField(models.TextField):
__metaclass__ = models.SubfieldBase
def formfield(self, **kwargs):
return super(JSONField, self).formfield(form_class=JSONFormField, **kwargs)
def __init__(self, *args, **kwargs):
self.dump_kwargs = kwargs.pop('dump_kwargs', {'cls': Encoder})
self.load_kwargs = kwargs.pop('load_kwargs', {})
super(JSONField, self).__init__(*args, **kwargs)
def to_python(self, value):
"""Convert our string value to JSON after we load it from the DB"""
if isinstance(value, basestring):
try:
return json.loads(value, **self.load_kwargs)
except ValueError:
pass
return value
def get_db_prep_save(self, value, connection=None):
"""Convert our JSON object to a string before we save"""
if not isinstance(value, basestring):
value = json.dumps(value, **self.dump_kwargs)
return super(JSONField, self).get_db_prep_save(value, connection=connection)
class TrimmedCharFormField(forms.CharField):
def clean(self, value):
if value:
value = value.strip()
return super(TrimmedCharFormField, self).clean(value)
add_introspection_rules([], ["^common\.fields\.TrimmedCharField"])
class TrimmedCharField(models.CharField):
__metaclass__ = models.SubfieldBase
def formfield(self, **kwargs):
return super(TrimmedCharField, self).formfield(form_class=TrimmedCharFormField, **kwargs)
add_introspection_rules([], ["^common\.fields\.PhoneNumberField"])
class PhoneNumberField(models.CharField):
__metaclass__ = models.SubfieldBase
def get_db_prep_value(self, value, connection, prepared=False):
try:
return format_us_phone_number(value)
except NumberParseException:
return value
def to_python(self, value):
if isinstance(value, basestring) and value != '':
try:
value = format_number(parse(value,"US"),PhoneNumberFormat.INTERNATIONAL)
except NumberParseException:
pass
return value
def get_db_prep_save(self, value, **kwargs):
if value is None: return
try:
return format_us_phone_number(value)
except NumberParseException:
return value
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
try:
return format_number(parse(value,"US"),PhoneNumberFormat.INTERNATIONAL)
except NumberParseException:
return value
class CustomForeignKey(models.ForeignKey):
def __init__(self, *args, **kwargs):
try:
self.related_validation_manager = kwargs.pop('related_validation_manager')
except KeyError:
self.related_validation_manager = '_default_manager'
super(CustomForeignKey, self).__init__(*args, **kwargs)
def validate(self, value, model_instance):
if self.rel.parent_link:
return
super(models.ForeignKey, self).validate(value, model_instance)
if value is None:
return
using = router.db_for_read(model_instance.__class__, instance=model_instance)
qs = getattr(self.rel.to, self.related_validation_manager).using(using).filter(
**{self.rel.field_name: value}
)
qs = qs.complex_filter(self.rel.limit_choices_to)
if not qs.exists():
raise exceptions.ValidationError(self.error_messages['invalid'] % {
'model': self.rel.to._meta.verbose_name, 'pk': value})
add_introspection_rules([
(
[CustomForeignKey], # Class(es) these apply to
[], # Positional arguments (not used)
{ # Keyword argument
"related_validation_manager": ["related_validation_manager", {"default": "_default_manager"}],
},
),
], ["^common\.fields\.CustomForeignKey"])
# ISO 3166-1 country names and codes adapted from http://opencountrycodes.appspot.com/python/
COUNTRIES = (
('US', _('United States')),
('AF', _('Afghanistan')),
('AX', _('Aland Islands')),
('AL', _('Albania')),
('DZ', _('Algeria')),
('AS', _('American Samoa')),
('AD', _('Andorra')),
('AO', _('Angola')),
('AI', _('Anguilla')),
('AQ', _('Antarctica')),
('AG', _('Antigua and Barbuda')),
('AR', _('Argentina')),
('AM', _('Armenia')),
('AW', _('Aruba')),
('AU', _('Australia')),
('AT', _('Austria')),
('AZ', _('Azerbaijan')),
('BS', _('Bahamas')),
('BH', _('Bahrain')),
('BD', _('Bangladesh')),
('BB', _('Barbados')),
('BY', _('Belarus')),
('BE', _('Belgium')),
('BZ', _('Belize')),
('BJ', _('Benin')),
('BM', _('Bermuda')),
('BT', _('Bhutan')),
('BO', _('Bolivia')),
('BA', _('Bosnia and Herzegovina')),
('BW', _('Botswana')),
('BV', _('Bouvet Island')),
('BR', _('Brazil')),
('IO', _('British Indian Ocean Territory')),
('BN', _('Brunei Darussalam')),
('BG', _('Bulgaria')),
('BF', _('Burkina Faso')),
('BI', _('Burundi')),
('KH', _('Cambodia')),
('CM', _('Cameroon')),
('CA', _('Canada')),
('CV', _('Cape Verde')),
('KY', _('Cayman Islands')),
('CF', _('Central African Republic')),
('TD', _('Chad')),
('CL', _('Chile')),
('CN', _('China')),
('CX', _('Christmas Island')),
('CC', _('Cocos (Keeling) Islands')),
('CO', _('Colombia')),
('KM', _('Comoros')),
('CG', _('Congo')),
('CD', _('Congo, The Democratic Republic of the')),
('CK', _('Cook Islands')),
('CR', _('Costa Rica')),
('CI', _('Cote d\'Ivoire')),
('HR', _('Croatia')),
('CU', _('Cuba')),
('CY', _('Cyprus')),
('CZ', _('Czech Republic')),
('DK', _('Denmark')),
('DJ', _('Djibouti')),
('DM', _('Dominica')),
('DO', _('Dominican Republic')),
('EC', _('Ecuador')),
('EG', _('Egypt')),
('SV', _('El Salvador')),
('GQ', _('Equatorial Guinea')),
('ER', _('Eritrea')),
('EE', _('Estonia')),
('ET', _('Ethiopia')),
('FK', _('Falkland Islands (Malvinas)')),
('FO', _('Faroe Islands')),
('FJ', _('Fiji')),
('FI', _('Finland')),
('FR', _('France')),
('GF', _('French Guiana')),
('PF', _('French Polynesia')),
('TF', _('French Southern Territories')),
('GA', _('Gabon')),
('GM', _('Gambia')),
('GE', _('Georgia')),
('DE', _('Germany')),
('GH', _('Ghana')),
('GI', _('Gibraltar')),
('GR', _('Greece')),
('GL', _('Greenland')),
('GD', _('Grenada')),
('GP', _('Guadeloupe')),
('GU', _('Guam')),
('GT', _('Guatemala')),
('GG', _('Guernsey')),
('GN', _('Guinea')),
('GW', _('Guinea-Bissau')),
('GY', _('Guyana')),
('HT', _('Haiti')),
('HM', _('Heard Island and McDonald Islands')),
('VA', _('Holy See (Vatican City State)')),
('HN', _('Honduras')),
('HK', _('Hong Kong')),
('HU', _('Hungary')),
('IS', _('Iceland')),
('IN', _('India')),
('ID', _('Indonesia')),
('IR', _('Iran, Islamic Republic of')),
('IQ', _('Iraq')),
('IE', _('Ireland')),
('IM', _('Isle of Man')),
('IL', _('Israel')),
('IT', _('Italy')),
('JM', _('Jamaica')),
('JP', _('Japan')),
('JE', _('Jersey')),
('JO', _('Jordan')),
('KZ', _('Kazakhstan')),
('KE', _('Kenya')),
('KI', _('Kiribati')),
('KP', _('Korea, Democratic People\'s Republic of')),
('KR', _('Korea, Republic of')),
('KW', _('Kuwait')),
('KG', _('Kyrgyzstan')),
('LA', _('Lao People\'s Democratic Republic')),
('LV', _('Latvia')),
('LB', _('Lebanon')),
('LS', _('Lesotho')),
('LR', _('Liberia')),
('LY', _('Libyan Arab Jamahiriya')),
('LI', _('Liechtenstein')),
('LT', _('Lithuania')),
('LU', _('Luxembourg')),
('MO', _('Macao')),
('MK', _('Macedonia, The Former Yugoslav Republic of')),
('MG', _('Madagascar')),
('MW', _('Malawi')),
('MY', _('Malaysia')),
('MV', _('Maldives')),
('ML', _('Mali')),
('MT', _('Malta')),
('MH', _('Marshall Islands')),
('MQ', _('Martinique')),
('MR', _('Mauritania')),
('MU', _('Mauritius')),
('YT', _('Mayotte')),
('MX', _('Mexico')),
('FM', _('Micronesia, Federated States of')),
('MD', _('Moldova')),
('MC', _('Monaco')),
('MN', _('Mongolia')),
('ME', _('Montenegro')),
('MS', _('Montserrat')),
('MA', _('Morocco')),
('MZ', _('Mozambique')),
('MM', _('Myanmar')),
('NA', _('Namibia')),
('NR', _('Nauru')),
('NP', _('Nepal')),
('NL', _('Netherlands')),
('AN', _('Netherlands Antilles')),
('NC', _('New Caledonia')),
('NZ', _('New Zealand')),
('NI', _('Nicaragua')),
('NE', _('Niger')),
('NG', _('Nigeria')),
('NU', _('Niue')),
('NF', _('Norfolk Island')),
('MP', _('Northern Mariana Islands')),
('NO', _('Norway')),
('OM', _('Oman')),
('PK', _('Pakistan')),
('PW', _('Palau')),
('PS', _('Palestinian Territory, Occupied')),
('PA', _('Panama')),
('PG', _('Papua New Guinea')),
('PY', _('Paraguay')),
('PE', _('Peru')),
('PH', _('Philippines')),
('PN', _('Pitcairn')),
('PL', _('Poland')),
('PT', _('Portugal')),
('PR', _('Puerto Rico')),
('QA', _('Qatar')),
('RE', _('Reunion')),
('RO', _('Romania')),
('RU', _('Russian Federation')),
('RW', _('Rwanda')),
('BL', _('Saint Barthelemy')),
('SH', _('Saint Helena')),
('KN', _('Saint Kitts and Nevis')),
('LC', _('Saint Lucia')),
('MF', _('Saint Martin')),
('PM', _('Saint Pierre and Miquelon')),
('VC', _('Saint Vincent and the Grenadines')),
('WS', _('Samoa')),
('SM', _('San Marino')),
('ST', _('Sao Tome and Principe')),
('SA', _('Saudi Arabia')),
('SN', _('Senegal')),
('RS', _('Serbia')),
('SC', _('Seychelles')),
('SL', _('Sierra Leone')),
('SG', _('Singapore')),
('SK', _('Slovakia')),
('SI', _('Slovenia')),
('SB', _('Solomon Islands')),
('SO', _('Somalia')),
('ZA', _('South Africa')),
('GS', _('South Georgia and the South Sandwich Islands')),
('ES', _('Spain')),
('LK', _('Sri Lanka')),
('SD', _('Sudan')),
('SR', _('Suriname')),
('SJ', _('Svalbard and Jan Mayen')),
('SZ', _('Swaziland')),
('SE', _('Sweden')),
('CH', _('Switzerland')),
('SY', _('Syrian Arab Republic')),
('TW', _('Taiwan, Province of China')),
('TJ', _('Tajikistan')),
('TZ', _('Tanzania, United Republic of')),
('TH', _('Thailand')),
('TL', _('Timor-Leste')),
('TG', _('Togo')),
('TK', _('Tokelau')),
('TO', _('Tonga')),
('TT', _('Trinidad and Tobago')),
('TN', _('Tunisia')),
('TR', _('Turkey')),
('TM', _('Turkmenistan')),
('TC', _('Turks and Caicos Islands')),
('TV', _('Tuvalu')),
('UG', _('Uganda')),
('UA', _('Ukraine')),
('AE', _('United Arab Emirates')),
('GB', _('United Kingdom')),
('US', _('United States')),
('UM', _('United States Minor Outlying Islands')),
('UY', _('Uruguay')),
('UZ', _('Uzbekistan')),
('VU', _('Vanuatu')),
('VE', _('Venezuela')),
('VN', _('Viet Nam')),
('VG', _('Virgin Islands, British')),
('VI', _('Virgin Islands, U.S.')),
('WF', _('Wallis and Futuna')),
('EH', _('Western Sahara')),
('YE', _('Yemen')),
('ZM', _('Zambia')),
('ZW', _('Zimbabwe')),
)
add_introspection_rules([], ["^common\.fields\.CountryField"])
class CountryField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('max_length', 2)
kwargs.setdefault('choices', COUNTRIES)
super(CountryField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return "CharField"
add_introspection_rules([], ["^common\.fields\.BlobField"])
class BlobField(models.TextField):
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
return 'longblob'
else:
# Uh, whatever.
return super(BlobField, self).db_type(connection)