|
1 import copy |
|
2 import datetime |
|
3 import os |
|
4 import time |
|
5 try: |
|
6 import decimal |
|
7 except ImportError: |
|
8 from django.utils import _decimal as decimal # for Python 2.3 |
|
9 |
|
10 from django.db import get_creation_module |
|
11 from django.db.models import signals |
|
12 from django.db.models.query_utils import QueryWrapper |
|
13 from django.dispatch import dispatcher |
|
14 from django.conf import settings |
|
15 from django.core import validators |
|
16 from django import oldforms |
|
17 from django import newforms as forms |
|
18 from django.core.exceptions import ObjectDoesNotExist |
|
19 from django.utils.functional import curry |
|
20 from django.utils.itercompat import tee |
|
21 from django.utils.text import capfirst |
|
22 from django.utils.translation import ugettext_lazy, ugettext as _ |
|
23 from django.utils.encoding import smart_unicode, force_unicode, smart_str |
|
24 from django.utils.maxlength import LegacyMaxlength |
|
25 |
|
26 class NOT_PROVIDED: |
|
27 pass |
|
28 |
|
29 # Values for filter_interface. |
|
30 HORIZONTAL, VERTICAL = 1, 2 |
|
31 |
|
32 # The values to use for "blank" in SelectFields. Will be appended to the start of most "choices" lists. |
|
33 BLANK_CHOICE_DASH = [("", "---------")] |
|
34 BLANK_CHOICE_NONE = [("", "None")] |
|
35 |
|
36 # prepares a value for use in a LIKE query |
|
37 prep_for_like_query = lambda x: smart_unicode(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") |
|
38 |
|
39 # returns the <ul> class for a given radio_admin value |
|
40 get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') |
|
41 |
|
42 class FieldDoesNotExist(Exception): |
|
43 pass |
|
44 |
|
45 def manipulator_validator_unique(f, opts, self, field_data, all_data): |
|
46 "Validates that the value is unique for this field." |
|
47 lookup_type = f.get_validator_unique_lookup_type() |
|
48 try: |
|
49 old_obj = self.manager.get(**{lookup_type: field_data}) |
|
50 except ObjectDoesNotExist: |
|
51 return |
|
52 if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val(): |
|
53 return |
|
54 raise validators.ValidationError, _("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name} |
|
55 |
|
56 # A guide to Field parameters: |
|
57 # |
|
58 # * name: The name of the field specifed in the model. |
|
59 # * attname: The attribute to use on the model object. This is the same as |
|
60 # "name", except in the case of ForeignKeys, where "_id" is |
|
61 # appended. |
|
62 # * db_column: The db_column specified in the model (or None). |
|
63 # * column: The database column for this field. This is the same as |
|
64 # "attname", except if db_column is specified. |
|
65 # |
|
66 # Code that introspects values, or does other dynamic things, should use |
|
67 # attname. For example, this gets the primary key value of object "obj": |
|
68 # |
|
69 # getattr(obj, opts.pk.attname) |
|
70 |
|
71 class Field(object): |
|
72 # Provide backwards compatibility for the maxlength attribute and |
|
73 # argument for this class and all subclasses. |
|
74 __metaclass__ = LegacyMaxlength |
|
75 |
|
76 # Designates whether empty strings fundamentally are allowed at the |
|
77 # database level. |
|
78 empty_strings_allowed = True |
|
79 |
|
80 # These track each time a Field instance is created. Used to retain order. |
|
81 # The auto_creation_counter is used for fields that Django implicitly |
|
82 # creates, creation_counter is used for all user-specified fields. |
|
83 creation_counter = 0 |
|
84 auto_creation_counter = -1 |
|
85 |
|
86 def __init__(self, verbose_name=None, name=None, primary_key=False, |
|
87 max_length=None, unique=False, blank=False, null=False, |
|
88 db_index=False, core=False, rel=None, default=NOT_PROVIDED, |
|
89 editable=True, serialize=True, prepopulate_from=None, |
|
90 unique_for_date=None, unique_for_month=None, unique_for_year=None, |
|
91 validator_list=None, choices=None, radio_admin=None, help_text='', |
|
92 db_column=None, db_tablespace=None, auto_created=False): |
|
93 self.name = name |
|
94 self.verbose_name = verbose_name |
|
95 self.primary_key = primary_key |
|
96 self.max_length, self.unique = max_length, unique |
|
97 self.blank, self.null = blank, null |
|
98 # Oracle treats the empty string ('') as null, so coerce the null |
|
99 # option whenever '' is a possible value. |
|
100 if self.empty_strings_allowed and settings.DATABASE_ENGINE == 'oracle': |
|
101 self.null = True |
|
102 self.core, self.rel, self.default = core, rel, default |
|
103 self.editable = editable |
|
104 self.serialize = serialize |
|
105 self.validator_list = validator_list or [] |
|
106 self.prepopulate_from = prepopulate_from |
|
107 self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month |
|
108 self.unique_for_year = unique_for_year |
|
109 self._choices = choices or [] |
|
110 self.radio_admin = radio_admin |
|
111 self.help_text = help_text |
|
112 self.db_column = db_column |
|
113 self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE |
|
114 |
|
115 # Set db_index to True if the field has a relationship and doesn't explicitly set db_index. |
|
116 self.db_index = db_index |
|
117 |
|
118 # Adjust the appropriate creation counter, and save our local copy. |
|
119 if auto_created: |
|
120 self.creation_counter = Field.auto_creation_counter |
|
121 Field.auto_creation_counter -= 1 |
|
122 else: |
|
123 self.creation_counter = Field.creation_counter |
|
124 Field.creation_counter += 1 |
|
125 |
|
126 def __cmp__(self, other): |
|
127 # This is needed because bisect does not take a comparison function. |
|
128 return cmp(self.creation_counter, other.creation_counter) |
|
129 |
|
130 def __deepcopy__(self, memodict): |
|
131 # We don't have to deepcopy very much here, since most things are not |
|
132 # intended to be altered after initial creation. |
|
133 obj = copy.copy(self) |
|
134 if self.rel: |
|
135 obj.rel = copy.copy(self.rel) |
|
136 memodict[id(self)] = obj |
|
137 return obj |
|
138 |
|
139 def to_python(self, value): |
|
140 """ |
|
141 Converts the input value into the expected Python data type, raising |
|
142 validators.ValidationError if the data can't be converted. Returns the |
|
143 converted value. Subclasses should override this. |
|
144 """ |
|
145 return value |
|
146 |
|
147 def db_type(self): |
|
148 """ |
|
149 Returns the database column data type for this field, taking into |
|
150 account the DATABASE_ENGINE setting. |
|
151 """ |
|
152 # The default implementation of this method looks at the |
|
153 # backend-specific DATA_TYPES dictionary, looking up the field by its |
|
154 # "internal type". |
|
155 # |
|
156 # A Field class can implement the get_internal_type() method to specify |
|
157 # which *preexisting* Django Field class it's most similar to -- i.e., |
|
158 # an XMLField is represented by a TEXT column type, which is the same |
|
159 # as the TextField Django field type, which means XMLField's |
|
160 # get_internal_type() returns 'TextField'. |
|
161 # |
|
162 # But the limitation of the get_internal_type() / DATA_TYPES approach |
|
163 # is that it cannot handle database column types that aren't already |
|
164 # mapped to one of the built-in Django field types. In this case, you |
|
165 # can implement db_type() instead of get_internal_type() to specify |
|
166 # exactly which wacky database column type you want to use. |
|
167 try: |
|
168 return get_creation_module().DATA_TYPES[self.get_internal_type()] % self.__dict__ |
|
169 except KeyError: |
|
170 return None |
|
171 |
|
172 def validate_full(self, field_data, all_data): |
|
173 """ |
|
174 Returns a list of errors for this field. This is the main interface, |
|
175 as it encapsulates some basic validation logic used by all fields. |
|
176 Subclasses should implement validate(), not validate_full(). |
|
177 """ |
|
178 if not self.blank and not field_data: |
|
179 return [_('This field is required.')] |
|
180 try: |
|
181 self.validate(field_data, all_data) |
|
182 except validators.ValidationError, e: |
|
183 return e.messages |
|
184 return [] |
|
185 |
|
186 def validate(self, field_data, all_data): |
|
187 """ |
|
188 Raises validators.ValidationError if field_data has any errors. |
|
189 Subclasses should override this to specify field-specific validation |
|
190 logic. This method should assume field_data has already been converted |
|
191 into the appropriate data type by Field.to_python(). |
|
192 """ |
|
193 pass |
|
194 |
|
195 def set_attributes_from_name(self, name): |
|
196 self.name = name |
|
197 self.attname, self.column = self.get_attname_column() |
|
198 self.verbose_name = self.verbose_name or (name and name.replace('_', ' ')) |
|
199 |
|
200 def contribute_to_class(self, cls, name): |
|
201 self.set_attributes_from_name(name) |
|
202 cls._meta.add_field(self) |
|
203 if self.choices: |
|
204 setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) |
|
205 |
|
206 def get_attname(self): |
|
207 return self.name |
|
208 |
|
209 def get_attname_column(self): |
|
210 attname = self.get_attname() |
|
211 column = self.db_column or attname |
|
212 return attname, column |
|
213 |
|
214 def get_cache_name(self): |
|
215 return '_%s_cache' % self.name |
|
216 |
|
217 def get_internal_type(self): |
|
218 return self.__class__.__name__ |
|
219 |
|
220 def pre_save(self, model_instance, add): |
|
221 "Returns field's value just before saving." |
|
222 return getattr(model_instance, self.attname) |
|
223 |
|
224 def get_db_prep_save(self, value): |
|
225 "Returns field's value prepared for saving into a database." |
|
226 return value |
|
227 |
|
228 def get_db_prep_lookup(self, lookup_type, value): |
|
229 "Returns field's value prepared for database lookup." |
|
230 if hasattr(value, 'as_sql'): |
|
231 sql, params = value.as_sql() |
|
232 return QueryWrapper(('(%s)' % sql), params) |
|
233 if lookup_type in ('exact', 'regex', 'iregex', 'gt', 'gte', 'lt', 'lte', 'month', 'day', 'search'): |
|
234 return [value] |
|
235 elif lookup_type in ('range', 'in'): |
|
236 return value |
|
237 elif lookup_type in ('contains', 'icontains'): |
|
238 return ["%%%s%%" % prep_for_like_query(value)] |
|
239 elif lookup_type == 'iexact': |
|
240 return [prep_for_like_query(value)] |
|
241 elif lookup_type in ('startswith', 'istartswith'): |
|
242 return ["%s%%" % prep_for_like_query(value)] |
|
243 elif lookup_type in ('endswith', 'iendswith'): |
|
244 return ["%%%s" % prep_for_like_query(value)] |
|
245 elif lookup_type == 'isnull': |
|
246 return [] |
|
247 elif lookup_type == 'year': |
|
248 try: |
|
249 value = int(value) |
|
250 except ValueError: |
|
251 raise ValueError("The __year lookup type requires an integer argument") |
|
252 if settings.DATABASE_ENGINE == 'sqlite3': |
|
253 first = '%s-01-01' |
|
254 second = '%s-12-31 23:59:59.999999' |
|
255 elif settings.DATABASE_ENGINE == 'oracle' and self.get_internal_type() == 'DateField': |
|
256 first = '%s-01-01' |
|
257 second = '%s-12-31' |
|
258 else: |
|
259 first = '%s-01-01 00:00:00' |
|
260 second = '%s-12-31 23:59:59.999999' |
|
261 return [first % value, second % value] |
|
262 raise TypeError("Field has invalid lookup: %s" % lookup_type) |
|
263 |
|
264 def has_default(self): |
|
265 "Returns a boolean of whether this field has a default value." |
|
266 return self.default is not NOT_PROVIDED |
|
267 |
|
268 def get_default(self): |
|
269 "Returns the default value for this field." |
|
270 if self.default is not NOT_PROVIDED: |
|
271 if callable(self.default): |
|
272 return self.default() |
|
273 return force_unicode(self.default, strings_only=True) |
|
274 if not self.empty_strings_allowed or (self.null and settings.DATABASE_ENGINE != 'oracle'): |
|
275 return None |
|
276 return "" |
|
277 |
|
278 def get_manipulator_field_names(self, name_prefix): |
|
279 """ |
|
280 Returns a list of field names that this object adds to the manipulator. |
|
281 """ |
|
282 return [name_prefix + self.name] |
|
283 |
|
284 def prepare_field_objs_and_params(self, manipulator, name_prefix): |
|
285 params = {'validator_list': self.validator_list[:]} |
|
286 if self.max_length and not self.choices: # Don't give SelectFields a max_length parameter. |
|
287 params['max_length'] = self.max_length |
|
288 |
|
289 if self.choices: |
|
290 if self.radio_admin: |
|
291 field_objs = [oldforms.RadioSelectField] |
|
292 params['ul_class'] = get_ul_class(self.radio_admin) |
|
293 else: |
|
294 field_objs = [oldforms.SelectField] |
|
295 |
|
296 params['choices'] = self.get_choices_default() |
|
297 else: |
|
298 field_objs = self.get_manipulator_field_objs() |
|
299 return (field_objs, params) |
|
300 |
|
301 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
|
302 """ |
|
303 Returns a list of oldforms.FormField instances for this field. It |
|
304 calculates the choices at runtime, not at compile time. |
|
305 |
|
306 name_prefix is a prefix to prepend to the "field_name" argument. |
|
307 rel is a boolean specifying whether this field is in a related context. |
|
308 """ |
|
309 field_objs, params = self.prepare_field_objs_and_params(manipulator, name_prefix) |
|
310 |
|
311 # Add the "unique" validator(s). |
|
312 for field_name_list in opts.unique_together: |
|
313 if field_name_list[0] == self.name: |
|
314 params['validator_list'].append(getattr(manipulator, 'isUnique%s' % '_'.join(field_name_list))) |
|
315 |
|
316 # Add the "unique for..." validator(s). |
|
317 if self.unique_for_date: |
|
318 params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_date))) |
|
319 if self.unique_for_month: |
|
320 params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_month))) |
|
321 if self.unique_for_year: |
|
322 params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_year))) |
|
323 if self.unique or (self.primary_key and not rel): |
|
324 params['validator_list'].append(curry(manipulator_validator_unique, self, opts, manipulator)) |
|
325 |
|
326 # Only add is_required=True if the field cannot be blank. Primary keys |
|
327 # are a special case, and fields in a related context should set this |
|
328 # as False, because they'll be caught by a separate validator -- |
|
329 # RequiredIfOtherFieldGiven. |
|
330 params['is_required'] = not self.blank and not self.primary_key and not rel |
|
331 |
|
332 # BooleanFields (CheckboxFields) are a special case. They don't take |
|
333 # is_required. |
|
334 if isinstance(self, BooleanField): |
|
335 del params['is_required'] |
|
336 |
|
337 # If this field is in a related context, check whether any other fields |
|
338 # in the related object have core=True. If so, add a validator -- |
|
339 # RequiredIfOtherFieldsGiven -- to this FormField. |
|
340 if rel and not self.blank and not isinstance(self, AutoField) and not isinstance(self, FileField): |
|
341 # First, get the core fields, if any. |
|
342 core_field_names = [] |
|
343 for f in opts.fields: |
|
344 if f.core and f != self: |
|
345 core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
|
346 # Now, if there are any, add the validator to this FormField. |
|
347 if core_field_names: |
|
348 params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, ugettext_lazy("This field is required."))) |
|
349 |
|
350 # Finally, add the field_names. |
|
351 field_names = self.get_manipulator_field_names(name_prefix) |
|
352 return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)] |
|
353 |
|
354 def get_validator_unique_lookup_type(self): |
|
355 return '%s__exact' % self.name |
|
356 |
|
357 def get_manipulator_new_data(self, new_data, rel=False): |
|
358 """ |
|
359 Given the full new_data dictionary (from the manipulator), returns this |
|
360 field's data. |
|
361 """ |
|
362 if rel: |
|
363 return new_data.get(self.name, [self.get_default()])[0] |
|
364 val = new_data.get(self.name, self.get_default()) |
|
365 if not self.empty_strings_allowed and val == '' and self.null: |
|
366 val = None |
|
367 return val |
|
368 |
|
369 def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): |
|
370 "Returns a list of tuples used as SelectField choices for this field." |
|
371 first_choice = include_blank and blank_choice or [] |
|
372 if self.choices: |
|
373 return first_choice + list(self.choices) |
|
374 rel_model = self.rel.to |
|
375 if hasattr(self.rel, 'get_related_field'): |
|
376 lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
|
377 else: |
|
378 lst = [(x._get_pk_val(), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
|
379 return first_choice + lst |
|
380 |
|
381 def get_choices_default(self): |
|
382 if self.radio_admin: |
|
383 return self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE) |
|
384 else: |
|
385 return self.get_choices() |
|
386 |
|
387 def _get_val_from_obj(self, obj): |
|
388 if obj: |
|
389 return getattr(obj, self.attname) |
|
390 else: |
|
391 return self.get_default() |
|
392 |
|
393 def flatten_data(self, follow, obj=None): |
|
394 """ |
|
395 Returns a dictionary mapping the field's manipulator field names to its |
|
396 "flattened" string values for the admin view. obj is the instance to |
|
397 extract the values from. |
|
398 """ |
|
399 return {self.attname: self._get_val_from_obj(obj)} |
|
400 |
|
401 def get_follow(self, override=None): |
|
402 if override != None: |
|
403 return override |
|
404 else: |
|
405 return self.editable |
|
406 |
|
407 def bind(self, fieldmapping, original, bound_field_class): |
|
408 return bound_field_class(self, fieldmapping, original) |
|
409 |
|
410 def _get_choices(self): |
|
411 if hasattr(self._choices, 'next'): |
|
412 choices, self._choices = tee(self._choices) |
|
413 return choices |
|
414 else: |
|
415 return self._choices |
|
416 choices = property(_get_choices) |
|
417 |
|
418 def save_form_data(self, instance, data): |
|
419 setattr(instance, self.name, data) |
|
420 |
|
421 def formfield(self, form_class=forms.CharField, **kwargs): |
|
422 "Returns a django.newforms.Field instance for this database Field." |
|
423 defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} |
|
424 if self.choices: |
|
425 defaults['widget'] = forms.Select(choices=self.get_choices(include_blank=self.blank or not (self.has_default() or 'initial' in kwargs))) |
|
426 if self.has_default(): |
|
427 defaults['initial'] = self.get_default() |
|
428 defaults.update(kwargs) |
|
429 return form_class(**defaults) |
|
430 |
|
431 def value_from_object(self, obj): |
|
432 "Returns the value of this field in the given model instance." |
|
433 return getattr(obj, self.attname) |
|
434 |
|
435 class AutoField(Field): |
|
436 empty_strings_allowed = False |
|
437 def __init__(self, *args, **kwargs): |
|
438 assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__ |
|
439 kwargs['blank'] = True |
|
440 Field.__init__(self, *args, **kwargs) |
|
441 |
|
442 def to_python(self, value): |
|
443 if value is None: |
|
444 return value |
|
445 try: |
|
446 return int(value) |
|
447 except (TypeError, ValueError): |
|
448 raise validators.ValidationError, _("This value must be an integer.") |
|
449 |
|
450 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
|
451 if not rel: |
|
452 return [] # Don't add a FormField unless it's in a related context. |
|
453 return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
|
454 |
|
455 def get_manipulator_field_objs(self): |
|
456 return [oldforms.HiddenField] |
|
457 |
|
458 def get_manipulator_new_data(self, new_data, rel=False): |
|
459 # Never going to be called |
|
460 # Not in main change pages |
|
461 # ignored in related context |
|
462 if not rel: |
|
463 return None |
|
464 return Field.get_manipulator_new_data(self, new_data, rel) |
|
465 |
|
466 def contribute_to_class(self, cls, name): |
|
467 assert not cls._meta.has_auto_field, "A model can't have more than one AutoField." |
|
468 super(AutoField, self).contribute_to_class(cls, name) |
|
469 cls._meta.has_auto_field = True |
|
470 cls._meta.auto_field = self |
|
471 |
|
472 def formfield(self, **kwargs): |
|
473 return None |
|
474 |
|
475 class BooleanField(Field): |
|
476 def __init__(self, *args, **kwargs): |
|
477 kwargs['blank'] = True |
|
478 Field.__init__(self, *args, **kwargs) |
|
479 |
|
480 def get_internal_type(self): |
|
481 return "BooleanField" |
|
482 |
|
483 def to_python(self, value): |
|
484 if value in (True, False): return value |
|
485 if value in ('t', 'True', '1'): return True |
|
486 if value in ('f', 'False', '0'): return False |
|
487 raise validators.ValidationError, _("This value must be either True or False.") |
|
488 |
|
489 def get_manipulator_field_objs(self): |
|
490 return [oldforms.CheckboxField] |
|
491 |
|
492 def formfield(self, **kwargs): |
|
493 defaults = {'form_class': forms.BooleanField} |
|
494 defaults.update(kwargs) |
|
495 return super(BooleanField, self).formfield(**defaults) |
|
496 |
|
497 class CharField(Field): |
|
498 def get_manipulator_field_objs(self): |
|
499 return [oldforms.TextField] |
|
500 |
|
501 def get_internal_type(self): |
|
502 return "CharField" |
|
503 |
|
504 def to_python(self, value): |
|
505 if isinstance(value, basestring): |
|
506 return value |
|
507 if value is None: |
|
508 if self.null: |
|
509 return value |
|
510 else: |
|
511 raise validators.ValidationError, ugettext_lazy("This field cannot be null.") |
|
512 return smart_unicode(value) |
|
513 |
|
514 def formfield(self, **kwargs): |
|
515 defaults = {'max_length': self.max_length} |
|
516 defaults.update(kwargs) |
|
517 return super(CharField, self).formfield(**defaults) |
|
518 |
|
519 # TODO: Maybe move this into contrib, because it's specialized. |
|
520 class CommaSeparatedIntegerField(CharField): |
|
521 def get_manipulator_field_objs(self): |
|
522 return [oldforms.CommaSeparatedIntegerField] |
|
523 |
|
524 class DateField(Field): |
|
525 empty_strings_allowed = False |
|
526 def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
|
527 self.auto_now, self.auto_now_add = auto_now, auto_now_add |
|
528 #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. |
|
529 if auto_now or auto_now_add: |
|
530 kwargs['editable'] = False |
|
531 kwargs['blank'] = True |
|
532 Field.__init__(self, verbose_name, name, **kwargs) |
|
533 |
|
534 def get_internal_type(self): |
|
535 return "DateField" |
|
536 |
|
537 def to_python(self, value): |
|
538 if value is None: |
|
539 return value |
|
540 if isinstance(value, datetime.datetime): |
|
541 return value.date() |
|
542 if isinstance(value, datetime.date): |
|
543 return value |
|
544 validators.isValidANSIDate(value, None) |
|
545 try: |
|
546 return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3]) |
|
547 except ValueError: |
|
548 raise validators.ValidationError, _('Enter a valid date in YYYY-MM-DD format.') |
|
549 |
|
550 def get_db_prep_lookup(self, lookup_type, value): |
|
551 if lookup_type == 'range': |
|
552 value = [smart_unicode(v) for v in value] |
|
553 elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte') and hasattr(value, 'strftime'): |
|
554 value = value.strftime('%Y-%m-%d') |
|
555 else: |
|
556 value = smart_unicode(value) |
|
557 return Field.get_db_prep_lookup(self, lookup_type, value) |
|
558 |
|
559 def pre_save(self, model_instance, add): |
|
560 if self.auto_now or (self.auto_now_add and add): |
|
561 value = datetime.datetime.now() |
|
562 setattr(model_instance, self.attname, value) |
|
563 return value |
|
564 else: |
|
565 return super(DateField, self).pre_save(model_instance, add) |
|
566 |
|
567 def contribute_to_class(self, cls, name): |
|
568 super(DateField,self).contribute_to_class(cls, name) |
|
569 if not self.null: |
|
570 setattr(cls, 'get_next_by_%s' % self.name, |
|
571 curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) |
|
572 setattr(cls, 'get_previous_by_%s' % self.name, |
|
573 curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) |
|
574 |
|
575 # Needed because of horrible auto_now[_add] behaviour wrt. editable |
|
576 def get_follow(self, override=None): |
|
577 if override != None: |
|
578 return override |
|
579 else: |
|
580 return self.editable or self.auto_now or self.auto_now_add |
|
581 |
|
582 def get_db_prep_save(self, value): |
|
583 # Casts dates into string format for entry into database. |
|
584 if value is not None: |
|
585 try: |
|
586 value = value.strftime('%Y-%m-%d') |
|
587 except AttributeError: |
|
588 # If value is already a string it won't have a strftime method, |
|
589 # so we'll just let it pass through. |
|
590 pass |
|
591 return Field.get_db_prep_save(self, value) |
|
592 |
|
593 def get_manipulator_field_objs(self): |
|
594 return [oldforms.DateField] |
|
595 |
|
596 def flatten_data(self, follow, obj=None): |
|
597 val = self._get_val_from_obj(obj) |
|
598 return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')} |
|
599 |
|
600 def formfield(self, **kwargs): |
|
601 defaults = {'form_class': forms.DateField} |
|
602 defaults.update(kwargs) |
|
603 return super(DateField, self).formfield(**defaults) |
|
604 |
|
605 class DateTimeField(DateField): |
|
606 def get_internal_type(self): |
|
607 return "DateTimeField" |
|
608 |
|
609 def to_python(self, value): |
|
610 if value is None: |
|
611 return value |
|
612 if isinstance(value, datetime.datetime): |
|
613 return value |
|
614 if isinstance(value, datetime.date): |
|
615 return datetime.datetime(value.year, value.month, value.day) |
|
616 try: # Seconds are optional, so try converting seconds first. |
|
617 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6]) |
|
618 except ValueError: |
|
619 try: # Try without seconds. |
|
620 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5]) |
|
621 except ValueError: # Try without hour/minutes/seconds. |
|
622 try: |
|
623 return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3]) |
|
624 except ValueError: |
|
625 raise validators.ValidationError, _('Enter a valid date/time in YYYY-MM-DD HH:MM format.') |
|
626 |
|
627 def get_db_prep_save(self, value): |
|
628 # Casts dates into string format for entry into database. |
|
629 if value is not None: |
|
630 # MySQL will throw a warning if microseconds are given, because it |
|
631 # doesn't support microseconds. |
|
632 if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): |
|
633 value = value.replace(microsecond=0) |
|
634 value = smart_unicode(value) |
|
635 return Field.get_db_prep_save(self, value) |
|
636 |
|
637 def get_db_prep_lookup(self, lookup_type, value): |
|
638 if lookup_type == 'range': |
|
639 value = [smart_unicode(v) for v in value] |
|
640 else: |
|
641 value = smart_unicode(value) |
|
642 return Field.get_db_prep_lookup(self, lookup_type, value) |
|
643 |
|
644 def get_manipulator_field_objs(self): |
|
645 return [oldforms.DateField, oldforms.TimeField] |
|
646 |
|
647 def get_manipulator_field_names(self, name_prefix): |
|
648 return [name_prefix + self.name + '_date', name_prefix + self.name + '_time'] |
|
649 |
|
650 def get_manipulator_new_data(self, new_data, rel=False): |
|
651 date_field, time_field = self.get_manipulator_field_names('') |
|
652 if rel: |
|
653 d = new_data.get(date_field, [None])[0] |
|
654 t = new_data.get(time_field, [None])[0] |
|
655 else: |
|
656 d = new_data.get(date_field, None) |
|
657 t = new_data.get(time_field, None) |
|
658 if d is not None and t is not None: |
|
659 return datetime.datetime.combine(d, t) |
|
660 return self.get_default() |
|
661 |
|
662 def flatten_data(self,follow, obj = None): |
|
663 val = self._get_val_from_obj(obj) |
|
664 date_field, time_field = self.get_manipulator_field_names('') |
|
665 return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''), |
|
666 time_field: (val is not None and val.strftime("%H:%M:%S") or '')} |
|
667 |
|
668 def formfield(self, **kwargs): |
|
669 defaults = {'form_class': forms.DateTimeField} |
|
670 defaults.update(kwargs) |
|
671 return super(DateTimeField, self).formfield(**defaults) |
|
672 |
|
673 class DecimalField(Field): |
|
674 empty_strings_allowed = False |
|
675 def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): |
|
676 self.max_digits, self.decimal_places = max_digits, decimal_places |
|
677 Field.__init__(self, verbose_name, name, **kwargs) |
|
678 |
|
679 def get_internal_type(self): |
|
680 return "DecimalField" |
|
681 |
|
682 def to_python(self, value): |
|
683 if value is None: |
|
684 return value |
|
685 try: |
|
686 return decimal.Decimal(value) |
|
687 except decimal.InvalidOperation: |
|
688 raise validators.ValidationError( |
|
689 _("This value must be a decimal number.")) |
|
690 |
|
691 def _format(self, value): |
|
692 if isinstance(value, basestring): |
|
693 return value |
|
694 else: |
|
695 return self.format_number(value) |
|
696 |
|
697 def format_number(self, value): |
|
698 """ |
|
699 Formats a number into a string with the requisite number of digits and |
|
700 decimal places. |
|
701 """ |
|
702 num_chars = self.max_digits |
|
703 # Allow for a decimal point |
|
704 if self.decimal_places > 0: |
|
705 num_chars += 1 |
|
706 # Allow for a minus sign |
|
707 if value < 0: |
|
708 num_chars += 1 |
|
709 |
|
710 return u"%.*f" % (self.decimal_places, value) |
|
711 |
|
712 def get_db_prep_save(self, value): |
|
713 if value is not None: |
|
714 value = self._format(value) |
|
715 return super(DecimalField, self).get_db_prep_save(value) |
|
716 |
|
717 def get_db_prep_lookup(self, lookup_type, value): |
|
718 if lookup_type == 'range': |
|
719 value = [self._format(v) for v in value] |
|
720 else: |
|
721 value = self._format(value) |
|
722 return super(DecimalField, self).get_db_prep_lookup(lookup_type, value) |
|
723 |
|
724 def get_manipulator_field_objs(self): |
|
725 return [curry(oldforms.DecimalField, max_digits=self.max_digits, decimal_places=self.decimal_places)] |
|
726 |
|
727 def formfield(self, **kwargs): |
|
728 defaults = { |
|
729 'max_digits': self.max_digits, |
|
730 'decimal_places': self.decimal_places, |
|
731 'form_class': forms.DecimalField, |
|
732 } |
|
733 defaults.update(kwargs) |
|
734 return super(DecimalField, self).formfield(**defaults) |
|
735 |
|
736 class EmailField(CharField): |
|
737 def __init__(self, *args, **kwargs): |
|
738 kwargs['max_length'] = kwargs.get('max_length', 75) |
|
739 CharField.__init__(self, *args, **kwargs) |
|
740 |
|
741 def get_manipulator_field_objs(self): |
|
742 return [oldforms.EmailField] |
|
743 |
|
744 def validate(self, field_data, all_data): |
|
745 validators.isValidEmail(field_data, all_data) |
|
746 |
|
747 def formfield(self, **kwargs): |
|
748 defaults = {'form_class': forms.EmailField} |
|
749 defaults.update(kwargs) |
|
750 return super(EmailField, self).formfield(**defaults) |
|
751 |
|
752 class FileField(Field): |
|
753 def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs): |
|
754 self.upload_to = upload_to |
|
755 kwargs['max_length'] = kwargs.get('max_length', 100) |
|
756 Field.__init__(self, verbose_name, name, **kwargs) |
|
757 |
|
758 def get_internal_type(self): |
|
759 return "FileField" |
|
760 |
|
761 def get_db_prep_save(self, value): |
|
762 "Returns field's value prepared for saving into a database." |
|
763 # Need to convert UploadedFile objects provided via a form to unicode for database insertion |
|
764 if value is None: |
|
765 return None |
|
766 return unicode(value) |
|
767 |
|
768 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
|
769 field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
|
770 if not self.blank: |
|
771 if rel: |
|
772 # This validator makes sure FileFields work in a related context. |
|
773 class RequiredFileField(object): |
|
774 def __init__(self, other_field_names, other_file_field_name): |
|
775 self.other_field_names = other_field_names |
|
776 self.other_file_field_name = other_file_field_name |
|
777 self.always_test = True |
|
778 def __call__(self, field_data, all_data): |
|
779 if not all_data.get(self.other_file_field_name, False): |
|
780 c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, ugettext_lazy("This field is required.")) |
|
781 c(field_data, all_data) |
|
782 # First, get the core fields, if any. |
|
783 core_field_names = [] |
|
784 for f in opts.fields: |
|
785 if f.core and f != self: |
|
786 core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
|
787 # Now, if there are any, add the validator to this FormField. |
|
788 if core_field_names: |
|
789 field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) |
|
790 else: |
|
791 v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, ugettext_lazy("This field is required.")) |
|
792 v.always_test = True |
|
793 field_list[0].validator_list.append(v) |
|
794 field_list[0].is_required = field_list[1].is_required = False |
|
795 |
|
796 # If the raw path is passed in, validate it's under the MEDIA_ROOT. |
|
797 def isWithinMediaRoot(field_data, all_data): |
|
798 f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data)) |
|
799 if not f.startswith(os.path.abspath(os.path.normpath(settings.MEDIA_ROOT))): |
|
800 raise validators.ValidationError, _("Enter a valid filename.") |
|
801 field_list[1].validator_list.append(isWithinMediaRoot) |
|
802 return field_list |
|
803 |
|
804 def contribute_to_class(self, cls, name): |
|
805 super(FileField, self).contribute_to_class(cls, name) |
|
806 setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self)) |
|
807 setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self)) |
|
808 setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self)) |
|
809 setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents, save=True: instance._save_FIELD_file(self, filename, raw_contents, save)) |
|
810 dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls) |
|
811 |
|
812 def delete_file(self, instance): |
|
813 if getattr(instance, self.attname): |
|
814 file_name = getattr(instance, 'get_%s_filename' % self.name)() |
|
815 # If the file exists and no other object of this type references it, |
|
816 # delete it from the filesystem. |
|
817 if os.path.exists(file_name) and \ |
|
818 not instance.__class__._default_manager.filter(**{'%s__exact' % self.name: getattr(instance, self.attname)}): |
|
819 os.remove(file_name) |
|
820 |
|
821 def get_manipulator_field_objs(self): |
|
822 return [oldforms.FileUploadField, oldforms.HiddenField] |
|
823 |
|
824 def get_manipulator_field_names(self, name_prefix): |
|
825 return [name_prefix + self.name + '_file', name_prefix + self.name] |
|
826 |
|
827 def save_file(self, new_data, new_object, original_object, change, rel, save=True): |
|
828 upload_field_name = self.get_manipulator_field_names('')[0] |
|
829 if new_data.get(upload_field_name, False): |
|
830 func = getattr(new_object, 'save_%s_file' % self.name) |
|
831 if rel: |
|
832 func(new_data[upload_field_name][0]["filename"], new_data[upload_field_name][0]["content"], save) |
|
833 else: |
|
834 func(new_data[upload_field_name]["filename"], new_data[upload_field_name]["content"], save) |
|
835 |
|
836 def get_directory_name(self): |
|
837 return os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.upload_to)))) |
|
838 |
|
839 def get_filename(self, filename): |
|
840 from django.utils.text import get_valid_filename |
|
841 f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename))) |
|
842 return os.path.normpath(f) |
|
843 |
|
844 def save_form_data(self, instance, data): |
|
845 from django.newforms.fields import UploadedFile |
|
846 if data and isinstance(data, UploadedFile): |
|
847 getattr(instance, "save_%s_file" % self.name)(data.filename, data.content, save=False) |
|
848 |
|
849 def formfield(self, **kwargs): |
|
850 defaults = {'form_class': forms.FileField} |
|
851 # If a file has been provided previously, then the form doesn't require |
|
852 # that a new file is provided this time. |
|
853 # The code to mark the form field as not required is used by |
|
854 # form_for_instance, but can probably be removed once form_for_instance |
|
855 # is gone. ModelForm uses a different method to check for an existing file. |
|
856 if 'initial' in kwargs: |
|
857 defaults['required'] = False |
|
858 defaults.update(kwargs) |
|
859 return super(FileField, self).formfield(**defaults) |
|
860 |
|
861 class FilePathField(Field): |
|
862 def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): |
|
863 self.path, self.match, self.recursive = path, match, recursive |
|
864 kwargs['max_length'] = kwargs.get('max_length', 100) |
|
865 Field.__init__(self, verbose_name, name, **kwargs) |
|
866 |
|
867 def formfield(self, **kwargs): |
|
868 defaults = { |
|
869 'path': self.path, |
|
870 'match': self.match, |
|
871 'recursive': self.recursive, |
|
872 'form_class': forms.FilePathField, |
|
873 } |
|
874 defaults.update(kwargs) |
|
875 return super(FilePathField, self).formfield(**defaults) |
|
876 |
|
877 def get_manipulator_field_objs(self): |
|
878 return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)] |
|
879 |
|
880 def get_internal_type(self): |
|
881 return "FilePathField" |
|
882 |
|
883 class FloatField(Field): |
|
884 empty_strings_allowed = False |
|
885 |
|
886 def get_manipulator_field_objs(self): |
|
887 return [oldforms.FloatField] |
|
888 |
|
889 def get_internal_type(self): |
|
890 return "FloatField" |
|
891 |
|
892 def formfield(self, **kwargs): |
|
893 defaults = {'form_class': forms.FloatField} |
|
894 defaults.update(kwargs) |
|
895 return super(FloatField, self).formfield(**defaults) |
|
896 |
|
897 class ImageField(FileField): |
|
898 def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): |
|
899 self.width_field, self.height_field = width_field, height_field |
|
900 FileField.__init__(self, verbose_name, name, **kwargs) |
|
901 |
|
902 def get_manipulator_field_objs(self): |
|
903 return [oldforms.ImageUploadField, oldforms.HiddenField] |
|
904 |
|
905 def contribute_to_class(self, cls, name): |
|
906 super(ImageField, self).contribute_to_class(cls, name) |
|
907 # Add get_BLAH_width and get_BLAH_height methods, but only if the |
|
908 # image field doesn't have width and height cache fields. |
|
909 if not self.width_field: |
|
910 setattr(cls, 'get_%s_width' % self.name, curry(cls._get_FIELD_width, field=self)) |
|
911 if not self.height_field: |
|
912 setattr(cls, 'get_%s_height' % self.name, curry(cls._get_FIELD_height, field=self)) |
|
913 |
|
914 def get_internal_type(self): |
|
915 return "ImageField" |
|
916 |
|
917 def save_file(self, new_data, new_object, original_object, change, rel, save=True): |
|
918 FileField.save_file(self, new_data, new_object, original_object, change, rel, save) |
|
919 # If the image has height and/or width field(s) and they haven't |
|
920 # changed, set the width and/or height field(s) back to their original |
|
921 # values. |
|
922 if change and (self.width_field or self.height_field) and save: |
|
923 if self.width_field: |
|
924 setattr(new_object, self.width_field, getattr(original_object, self.width_field)) |
|
925 if self.height_field: |
|
926 setattr(new_object, self.height_field, getattr(original_object, self.height_field)) |
|
927 new_object.save() |
|
928 |
|
929 def formfield(self, **kwargs): |
|
930 defaults = {'form_class': forms.ImageField} |
|
931 defaults.update(kwargs) |
|
932 return super(ImageField, self).formfield(**defaults) |
|
933 |
|
934 class IntegerField(Field): |
|
935 empty_strings_allowed = False |
|
936 def get_manipulator_field_objs(self): |
|
937 return [oldforms.IntegerField] |
|
938 |
|
939 def get_internal_type(self): |
|
940 return "IntegerField" |
|
941 |
|
942 def formfield(self, **kwargs): |
|
943 defaults = {'form_class': forms.IntegerField} |
|
944 defaults.update(kwargs) |
|
945 return super(IntegerField, self).formfield(**defaults) |
|
946 |
|
947 class IPAddressField(Field): |
|
948 empty_strings_allowed = False |
|
949 def __init__(self, *args, **kwargs): |
|
950 kwargs['max_length'] = 15 |
|
951 Field.__init__(self, *args, **kwargs) |
|
952 |
|
953 def get_manipulator_field_objs(self): |
|
954 return [oldforms.IPAddressField] |
|
955 |
|
956 def get_internal_type(self): |
|
957 return "IPAddressField" |
|
958 |
|
959 def validate(self, field_data, all_data): |
|
960 validators.isValidIPAddress4(field_data, None) |
|
961 |
|
962 def formfield(self, **kwargs): |
|
963 defaults = {'form_class': forms.IPAddressField} |
|
964 defaults.update(kwargs) |
|
965 return super(IPAddressField, self).formfield(**defaults) |
|
966 |
|
967 class NullBooleanField(Field): |
|
968 empty_strings_allowed = False |
|
969 def __init__(self, *args, **kwargs): |
|
970 kwargs['null'] = True |
|
971 Field.__init__(self, *args, **kwargs) |
|
972 |
|
973 def get_internal_type(self): |
|
974 return "NullBooleanField" |
|
975 |
|
976 def to_python(self, value): |
|
977 if value in (None, True, False): return value |
|
978 if value in ('None'): return None |
|
979 if value in ('t', 'True', '1'): return True |
|
980 if value in ('f', 'False', '0'): return False |
|
981 raise validators.ValidationError, _("This value must be either None, True or False.") |
|
982 |
|
983 def get_manipulator_field_objs(self): |
|
984 return [oldforms.NullBooleanField] |
|
985 |
|
986 def formfield(self, **kwargs): |
|
987 defaults = {'form_class': forms.NullBooleanField} |
|
988 defaults.update(kwargs) |
|
989 return super(NullBooleanField, self).formfield(**defaults) |
|
990 |
|
991 class PhoneNumberField(IntegerField): |
|
992 def get_manipulator_field_objs(self): |
|
993 return [oldforms.PhoneNumberField] |
|
994 |
|
995 def get_internal_type(self): |
|
996 return "PhoneNumberField" |
|
997 |
|
998 def validate(self, field_data, all_data): |
|
999 validators.isValidPhone(field_data, all_data) |
|
1000 |
|
1001 def formfield(self, **kwargs): |
|
1002 from django.contrib.localflavor.us.forms import USPhoneNumberField |
|
1003 defaults = {'form_class': USPhoneNumberField} |
|
1004 defaults.update(kwargs) |
|
1005 return super(PhoneNumberField, self).formfield(**defaults) |
|
1006 |
|
1007 class PositiveIntegerField(IntegerField): |
|
1008 def get_manipulator_field_objs(self): |
|
1009 return [oldforms.PositiveIntegerField] |
|
1010 |
|
1011 def get_internal_type(self): |
|
1012 return "PositiveIntegerField" |
|
1013 |
|
1014 def formfield(self, **kwargs): |
|
1015 defaults = {'min_value': 0} |
|
1016 defaults.update(kwargs) |
|
1017 return super(PositiveIntegerField, self).formfield(**defaults) |
|
1018 |
|
1019 class PositiveSmallIntegerField(IntegerField): |
|
1020 def get_manipulator_field_objs(self): |
|
1021 return [oldforms.PositiveSmallIntegerField] |
|
1022 |
|
1023 def get_internal_type(self): |
|
1024 return "PositiveSmallIntegerField" |
|
1025 |
|
1026 def formfield(self, **kwargs): |
|
1027 defaults = {'min_value': 0} |
|
1028 defaults.update(kwargs) |
|
1029 return super(PositiveSmallIntegerField, self).formfield(**defaults) |
|
1030 |
|
1031 class SlugField(CharField): |
|
1032 def __init__(self, *args, **kwargs): |
|
1033 kwargs['max_length'] = kwargs.get('max_length', 50) |
|
1034 kwargs.setdefault('validator_list', []).append(validators.isSlug) |
|
1035 # Set db_index=True unless it's been set manually. |
|
1036 if 'db_index' not in kwargs: |
|
1037 kwargs['db_index'] = True |
|
1038 super(SlugField, self).__init__(*args, **kwargs) |
|
1039 |
|
1040 def get_internal_type(self): |
|
1041 return "SlugField" |
|
1042 |
|
1043 class SmallIntegerField(IntegerField): |
|
1044 def get_manipulator_field_objs(self): |
|
1045 return [oldforms.SmallIntegerField] |
|
1046 |
|
1047 def get_internal_type(self): |
|
1048 return "SmallIntegerField" |
|
1049 |
|
1050 class TextField(Field): |
|
1051 def get_manipulator_field_objs(self): |
|
1052 return [oldforms.LargeTextField] |
|
1053 |
|
1054 def get_internal_type(self): |
|
1055 return "TextField" |
|
1056 |
|
1057 def formfield(self, **kwargs): |
|
1058 defaults = {'widget': forms.Textarea} |
|
1059 defaults.update(kwargs) |
|
1060 return super(TextField, self).formfield(**defaults) |
|
1061 |
|
1062 class TimeField(Field): |
|
1063 empty_strings_allowed = False |
|
1064 def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
|
1065 self.auto_now, self.auto_now_add = auto_now, auto_now_add |
|
1066 if auto_now or auto_now_add: |
|
1067 kwargs['editable'] = False |
|
1068 Field.__init__(self, verbose_name, name, **kwargs) |
|
1069 |
|
1070 def get_internal_type(self): |
|
1071 return "TimeField" |
|
1072 |
|
1073 def get_db_prep_lookup(self, lookup_type, value): |
|
1074 if settings.DATABASE_ENGINE == 'oracle': |
|
1075 # Oracle requires a date in order to parse. |
|
1076 def prep(value): |
|
1077 if isinstance(value, datetime.time): |
|
1078 value = datetime.datetime.combine(datetime.date(1900, 1, 1), value) |
|
1079 return smart_unicode(value) |
|
1080 else: |
|
1081 prep = smart_unicode |
|
1082 if lookup_type == 'range': |
|
1083 value = [prep(v) for v in value] |
|
1084 else: |
|
1085 value = prep(value) |
|
1086 return Field.get_db_prep_lookup(self, lookup_type, value) |
|
1087 |
|
1088 def pre_save(self, model_instance, add): |
|
1089 if self.auto_now or (self.auto_now_add and add): |
|
1090 value = datetime.datetime.now().time() |
|
1091 setattr(model_instance, self.attname, value) |
|
1092 return value |
|
1093 else: |
|
1094 return super(TimeField, self).pre_save(model_instance, add) |
|
1095 |
|
1096 def get_db_prep_save(self, value): |
|
1097 # Casts dates into string format for entry into database. |
|
1098 if value is not None: |
|
1099 # MySQL will throw a warning if microseconds are given, because it |
|
1100 # doesn't support microseconds. |
|
1101 if settings.DATABASE_ENGINE == 'mysql' and hasattr(value, 'microsecond'): |
|
1102 value = value.replace(microsecond=0) |
|
1103 if settings.DATABASE_ENGINE == 'oracle': |
|
1104 # cx_Oracle expects a datetime.datetime to persist into TIMESTAMP field. |
|
1105 if isinstance(value, datetime.time): |
|
1106 value = datetime.datetime(1900, 1, 1, value.hour, value.minute, |
|
1107 value.second, value.microsecond) |
|
1108 elif isinstance(value, basestring): |
|
1109 value = datetime.datetime(*(time.strptime(value, '%H:%M:%S')[:6])) |
|
1110 else: |
|
1111 value = smart_unicode(value) |
|
1112 return Field.get_db_prep_save(self, value) |
|
1113 |
|
1114 def get_manipulator_field_objs(self): |
|
1115 return [oldforms.TimeField] |
|
1116 |
|
1117 def flatten_data(self,follow, obj = None): |
|
1118 val = self._get_val_from_obj(obj) |
|
1119 return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')} |
|
1120 |
|
1121 def formfield(self, **kwargs): |
|
1122 defaults = {'form_class': forms.TimeField} |
|
1123 defaults.update(kwargs) |
|
1124 return super(TimeField, self).formfield(**defaults) |
|
1125 |
|
1126 class URLField(CharField): |
|
1127 def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): |
|
1128 kwargs['max_length'] = kwargs.get('max_length', 200) |
|
1129 if verify_exists: |
|
1130 kwargs.setdefault('validator_list', []).append(validators.isExistingURL) |
|
1131 self.verify_exists = verify_exists |
|
1132 CharField.__init__(self, verbose_name, name, **kwargs) |
|
1133 |
|
1134 def get_manipulator_field_objs(self): |
|
1135 return [oldforms.URLField] |
|
1136 |
|
1137 def formfield(self, **kwargs): |
|
1138 defaults = {'form_class': forms.URLField, 'verify_exists': self.verify_exists} |
|
1139 defaults.update(kwargs) |
|
1140 return super(URLField, self).formfield(**defaults) |
|
1141 |
|
1142 class USStateField(Field): |
|
1143 def get_manipulator_field_objs(self): |
|
1144 return [oldforms.USStateField] |
|
1145 |
|
1146 def get_internal_type(self): |
|
1147 return "USStateField" |
|
1148 |
|
1149 def formfield(self, **kwargs): |
|
1150 from django.contrib.localflavor.us.forms import USStateSelect |
|
1151 defaults = {'widget': USStateSelect} |
|
1152 defaults.update(kwargs) |
|
1153 return super(USStateField, self).formfield(**defaults) |
|
1154 |
|
1155 class XMLField(TextField): |
|
1156 def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): |
|
1157 self.schema_path = schema_path |
|
1158 Field.__init__(self, verbose_name, name, **kwargs) |
|
1159 |
|
1160 def get_manipulator_field_objs(self): |
|
1161 return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)] |
|
1162 |
|
1163 class OrderingField(IntegerField): |
|
1164 empty_strings_allowed=False |
|
1165 def __init__(self, with_respect_to, **kwargs): |
|
1166 self.wrt = with_respect_to |
|
1167 kwargs['null'] = True |
|
1168 IntegerField.__init__(self, **kwargs ) |
|
1169 |
|
1170 def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
|
1171 return [oldforms.HiddenField(name_prefix + self.name)] |