| 1 | from django.db.models import signals |
| 2 | from django.dispatch import dispatcher |
| 3 | from django.conf import settings |
| 4 | from django.core import validators |
| 5 | from django import oldforms |
| 6 | from django import newforms as forms |
| 7 | from django.core.exceptions import ObjectDoesNotExist |
| 8 | from django.utils.functional import curry |
| 9 | from django.utils.itercompat import tee |
| 10 | from django.utils.text import capfirst |
| 11 | from django.utils.translation import gettext, gettext_lazy |
| 12 | import datetime, os, time |
| 13 | |
| 14 | class NOT_PROVIDED: |
| 15 | pass |
| 16 | |
| 17 | # Values for filter_interface. |
| 18 | HORIZONTAL, VERTICAL = 1, 2 |
| 19 | |
| 20 | # The values to use for "blank" in SelectFields. Will be appended to the start of most "choices" lists. |
| 21 | BLANK_CHOICE_DASH = [("", "---------")] |
| 22 | BLANK_CHOICE_NONE = [("", "None")] |
| 23 | |
| 24 | # prepares a value for use in a LIKE query |
| 25 | prep_for_like_query = lambda x: str(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") |
| 26 | |
| 27 | # returns the <ul> class for a given radio_admin value |
| 28 | get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') |
| 29 | |
| 30 | class FieldDoesNotExist(Exception): |
| 31 | pass |
| 32 | |
| 33 | def manipulator_validator_unique(f, opts, self, field_data, all_data): |
| 34 | "Validates that the value is unique for this field." |
| 35 | lookup_type = f.get_validator_unique_lookup_type() |
| 36 | try: |
| 37 | old_obj = self.manager.get(**{lookup_type: field_data}) |
| 38 | except ObjectDoesNotExist: |
| 39 | return |
| 40 | if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val(): |
| 41 | return |
| 42 | raise validators.ValidationError, gettext("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name} |
| 43 | |
| 44 | # A guide to Field parameters: |
| 45 | # |
| 46 | # * name: The name of the field specifed in the model. |
| 47 | # * attname: The attribute to use on the model object. This is the same as |
| 48 | # "name", except in the case of ForeignKeys, where "_id" is |
| 49 | # appended. |
| 50 | # * db_column: The db_column specified in the model (or None). |
| 51 | # * column: The database column for this field. This is the same as |
| 52 | # "attname", except if db_column is specified. |
| 53 | # |
| 54 | # Code that introspects values, or does other dynamic things, should use |
| 55 | # attname. For example, this gets the primary key value of object "obj": |
| 56 | # |
| 57 | # getattr(obj, opts.pk.attname) |
| 58 | |
| 59 | class Field(object): |
| 60 | |
| 61 | # Designates whether empty strings fundamentally are allowed at the |
| 62 | # database level. |
| 63 | empty_strings_allowed = True |
| 64 | |
| 65 | # Tracks each time a Field instance is created. Used to retain order. |
| 66 | creation_counter = 0 |
| 67 | |
| 68 | def __init__(self, verbose_name=None, name=None, primary_key=False, |
| 69 | maxlength=None, unique=False, blank=False, null=False, db_index=False, |
| 70 | core=False, rel=None, default=NOT_PROVIDED, editable=True, |
| 71 | prepopulate_from=None, unique_for_date=None, unique_for_month=None, |
| 72 | unique_for_year=None, validator_list=None, choices=None, radio_admin=None, |
| 73 | help_text='', db_column=None): |
| 74 | self.name = name |
| 75 | self.verbose_name = verbose_name |
| 76 | self.primary_key = primary_key |
| 77 | self.maxlength, self.unique = maxlength, unique |
| 78 | self.blank, self.null = blank, null |
| 79 | self.core, self.rel, self.default = core, rel, default |
| 80 | self.editable = editable |
| 81 | self.validator_list = validator_list or [] |
| 82 | self.prepopulate_from = prepopulate_from |
| 83 | self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month |
| 84 | self.unique_for_year = unique_for_year |
| 85 | self._choices = choices or [] |
| 86 | self.radio_admin = radio_admin |
| 87 | self.help_text = help_text |
| 88 | self.db_column = db_column |
| 89 | |
| 90 | # Set db_index to True if the field has a relationship and doesn't explicitly set db_index. |
| 91 | self.db_index = db_index |
| 92 | |
| 93 | # Increase the creation counter, and save our local copy. |
| 94 | self.creation_counter = Field.creation_counter |
| 95 | Field.creation_counter += 1 |
| 96 | |
| 97 | def __cmp__(self, other): |
| 98 | # This is needed because bisect does not take a comparison function. |
| 99 | return cmp(self.creation_counter, other.creation_counter) |
| 100 | |
| 101 | def to_python(self, value): |
| 102 | """ |
| 103 | Converts the input value into the expected Python data type, raising |
| 104 | validators.ValidationError if the data can't be converted. Returns the |
| 105 | converted value. Subclasses should override this. |
| 106 | """ |
| 107 | return value |
| 108 | |
| 109 | def validate_full(self, field_data, all_data): |
| 110 | """ |
| 111 | Returns a list of errors for this field. This is the main interface, |
| 112 | as it encapsulates some basic validation logic used by all fields. |
| 113 | Subclasses should implement validate(), not validate_full(). |
| 114 | """ |
| 115 | if not self.blank and not field_data: |
| 116 | return [gettext_lazy('This field is required.')] |
| 117 | try: |
| 118 | self.validate(field_data, all_data) |
| 119 | except validators.ValidationError, e: |
| 120 | return e.messages |
| 121 | return [] |
| 122 | |
| 123 | def validate(self, field_data, all_data): |
| 124 | """ |
| 125 | Raises validators.ValidationError if field_data has any errors. |
| 126 | Subclasses should override this to specify field-specific validation |
| 127 | logic. This method should assume field_data has already been converted |
| 128 | into the appropriate data type by Field.to_python(). |
| 129 | """ |
| 130 | pass |
| 131 | |
| 132 | def set_attributes_from_name(self, name): |
| 133 | self.name = name |
| 134 | self.attname, self.column = self.get_attname_column() |
| 135 | self.verbose_name = self.verbose_name or (name and name.replace('_', ' ')) |
| 136 | |
| 137 | def contribute_to_class(self, cls, name): |
| 138 | self.set_attributes_from_name(name) |
| 139 | cls._meta.add_field(self) |
| 140 | if self.choices: |
| 141 | setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) |
| 142 | |
| 143 | def get_attname(self): |
| 144 | return self.name |
| 145 | |
| 146 | def get_attname_column(self): |
| 147 | attname = self.get_attname() |
| 148 | column = self.db_column or attname |
| 149 | return attname, column |
| 150 | |
| 151 | def get_cache_name(self): |
| 152 | return '_%s_cache' % self.name |
| 153 | |
| 154 | def get_internal_type(self): |
| 155 | return self.__class__.__name__ |
| 156 | |
| 157 | def pre_save(self, model_instance, add): |
| 158 | "Returns field's value just before saving." |
| 159 | return getattr(model_instance, self.attname) |
| 160 | |
| 161 | def get_db_prep_save(self, value): |
| 162 | "Returns field's value prepared for saving into a database." |
| 163 | return value |
| 164 | |
| 165 | def get_db_prep_lookup(self, lookup_type, value): |
| 166 | "Returns field's value prepared for database lookup." |
| 167 | if lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte', 'year', 'month', 'day', 'search'): |
| 168 | return [value] |
| 169 | elif lookup_type in ('range', 'in'): |
| 170 | return value |
| 171 | elif lookup_type in ('contains', 'icontains'): |
| 172 | return ["%%%s%%" % prep_for_like_query(value)] |
| 173 | elif lookup_type == 'iexact': |
| 174 | return [prep_for_like_query(value)] |
| 175 | elif lookup_type in ('startswith', 'istartswith'): |
| 176 | return ["%s%%" % prep_for_like_query(value)] |
| 177 | elif lookup_type in ('endswith', 'iendswith'): |
| 178 | return ["%%%s" % prep_for_like_query(value)] |
| 179 | elif lookup_type == 'isnull': |
| 180 | return [] |
| 181 | raise TypeError, "Field has invalid lookup: %s" % lookup_type |
| 182 | |
| 183 | def has_default(self): |
| 184 | "Returns a boolean of whether this field has a default value." |
| 185 | return self.default is not NOT_PROVIDED |
| 186 | |
| 187 | def get_default(self): |
| 188 | "Returns the default value for this field." |
| 189 | if self.default is not NOT_PROVIDED: |
| 190 | if callable(self.default): |
| 191 | return self.default() |
| 192 | return self.default |
| 193 | if not self.empty_strings_allowed or self.null: |
| 194 | return None |
| 195 | return "" |
| 196 | |
| 197 | def get_manipulator_field_names(self, name_prefix): |
| 198 | """ |
| 199 | Returns a list of field names that this object adds to the manipulator. |
| 200 | """ |
| 201 | return [name_prefix + self.name] |
| 202 | |
| 203 | def prepare_field_objs_and_params(self, manipulator, name_prefix): |
| 204 | params = {'validator_list': self.validator_list[:]} |
| 205 | if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter. |
| 206 | params['maxlength'] = self.maxlength |
| 207 | |
| 208 | if self.choices: |
| 209 | if self.radio_admin: |
| 210 | field_objs = [oldforms.RadioSelectField] |
| 211 | params['ul_class'] = get_ul_class(self.radio_admin) |
| 212 | else: |
| 213 | field_objs = [oldforms.SelectField] |
| 214 | |
| 215 | params['choices'] = self.get_choices_default() |
| 216 | else: |
| 217 | field_objs = self.get_manipulator_field_objs() |
| 218 | return (field_objs, params) |
| 219 | |
| 220 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 221 | """ |
| 222 | Returns a list of oldforms.FormField instances for this field. It |
| 223 | calculates the choices at runtime, not at compile time. |
| 224 | |
| 225 | name_prefix is a prefix to prepend to the "field_name" argument. |
| 226 | rel is a boolean specifying whether this field is in a related context. |
| 227 | """ |
| 228 | field_objs, params = self.prepare_field_objs_and_params(manipulator, name_prefix) |
| 229 | |
| 230 | # Add the "unique" validator(s). |
| 231 | for field_name_list in opts.unique_together: |
| 232 | if field_name_list[0] == self.name: |
| 233 | params['validator_list'].append(getattr(manipulator, 'isUnique%s' % '_'.join(field_name_list))) |
| 234 | |
| 235 | # Add the "unique for..." validator(s). |
| 236 | if self.unique_for_date: |
| 237 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_date))) |
| 238 | if self.unique_for_month: |
| 239 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_month))) |
| 240 | if self.unique_for_year: |
| 241 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_year))) |
| 242 | if self.unique or (self.primary_key and not rel): |
| 243 | params['validator_list'].append(curry(manipulator_validator_unique, self, opts, manipulator)) |
| 244 | |
| 245 | # Only add is_required=True if the field cannot be blank. Primary keys |
| 246 | # are a special case, and fields in a related context should set this |
| 247 | # as False, because they'll be caught by a separate validator -- |
| 248 | # RequiredIfOtherFieldGiven. |
| 249 | params['is_required'] = not self.blank and not self.primary_key and not rel |
| 250 | |
| 251 | # BooleanFields (CheckboxFields) are a special case. They don't take |
| 252 | # is_required. |
| 253 | if isinstance(self, BooleanField): |
| 254 | del params['is_required'] |
| 255 | |
| 256 | # If this field is in a related context, check whether any other fields |
| 257 | # in the related object have core=True. If so, add a validator -- |
| 258 | # RequiredIfOtherFieldsGiven -- to this FormField. |
| 259 | if rel and not self.blank and not isinstance(self, AutoField) and not isinstance(self, FileField): |
| 260 | # First, get the core fields, if any. |
| 261 | core_field_names = [] |
| 262 | for f in opts.fields: |
| 263 | if f.core and f != self: |
| 264 | core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
| 265 | # Now, if there are any, add the validator to this FormField. |
| 266 | if core_field_names: |
| 267 | params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, gettext_lazy("This field is required."))) |
| 268 | |
| 269 | # Finally, add the field_names. |
| 270 | field_names = self.get_manipulator_field_names(name_prefix) |
| 271 | return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)] |
| 272 | |
| 273 | def get_validator_unique_lookup_type(self): |
| 274 | return '%s__exact' % self.name |
| 275 | |
| 276 | def get_manipulator_new_data(self, new_data, rel=False): |
| 277 | """ |
| 278 | Given the full new_data dictionary (from the manipulator), returns this |
| 279 | field's data. |
| 280 | """ |
| 281 | if rel: |
| 282 | return new_data.get(self.name, [self.get_default()])[0] |
| 283 | val = new_data.get(self.name, self.get_default()) |
| 284 | if not self.empty_strings_allowed and val == '' and self.null: |
| 285 | val = None |
| 286 | return val |
| 287 | |
| 288 | def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): |
| 289 | "Returns a list of tuples used as SelectField choices for this field." |
| 290 | first_choice = include_blank and blank_choice or [] |
| 291 | if self.choices: |
| 292 | return first_choice + list(self.choices) |
| 293 | rel_model = self.rel.to |
| 294 | if hasattr(self.rel, 'get_related_field'): |
| 295 | lst = [(getattr(x, self.rel.get_related_field().attname), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
| 296 | else: |
| 297 | lst = [(x._get_pk_val(), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
| 298 | return first_choice + lst |
| 299 | |
| 300 | def get_choices_default(self): |
| 301 | if self.radio_admin: |
| 302 | return self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE) |
| 303 | else: |
| 304 | return self.get_choices() |
| 305 | |
| 306 | def _get_val_from_obj(self, obj): |
| 307 | if obj: |
| 308 | return getattr(obj, self.attname) |
| 309 | else: |
| 310 | return self.get_default() |
| 311 | |
| 312 | def flatten_data(self, follow, obj=None): |
| 313 | """ |
| 314 | Returns a dictionary mapping the field's manipulator field names to its |
| 315 | "flattened" string values for the admin view. obj is the instance to |
| 316 | extract the values from. |
| 317 | """ |
| 318 | return {self.attname: self._get_val_from_obj(obj)} |
| 319 | |
| 320 | def get_follow(self, override=None): |
| 321 | if override != None: |
| 322 | return override |
| 323 | else: |
| 324 | return self.editable |
| 325 | |
| 326 | def bind(self, fieldmapping, original, bound_field_class): |
| 327 | return bound_field_class(self, fieldmapping, original) |
| 328 | |
| 329 | def _get_choices(self): |
| 330 | if hasattr(self._choices, 'next'): |
| 331 | choices, self._choices = tee(self._choices) |
| 332 | return choices |
| 333 | else: |
| 334 | return self._choices |
| 335 | choices = property(_get_choices) |
| 336 | |
| 337 | def formfield(self): |
| 338 | "Returns a django.newforms.Field instance for this database Field." |
| 339 | # TODO: This is just a temporary default during development. |
| 340 | return forms.CharField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 341 | |
| 342 | class AutoField(Field): |
| 343 | empty_strings_allowed = False |
| 344 | def __init__(self, *args, **kwargs): |
| 345 | assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__ |
| 346 | kwargs['blank'] = True |
| 347 | Field.__init__(self, *args, **kwargs) |
| 348 | |
| 349 | def to_python(self, value): |
| 350 | if value is None: |
| 351 | return value |
| 352 | try: |
| 353 | return int(value) |
| 354 | except (TypeError, ValueError): |
| 355 | raise validators.ValidationError, gettext("This value must be an integer.") |
| 356 | |
| 357 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 358 | if not rel: |
| 359 | return [] # Don't add a FormField unless it's in a related context. |
| 360 | return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
| 361 | |
| 362 | def get_manipulator_field_objs(self): |
| 363 | return [oldforms.HiddenField] |
| 364 | |
| 365 | def get_manipulator_new_data(self, new_data, rel=False): |
| 366 | # Never going to be called |
| 367 | # Not in main change pages |
| 368 | # ignored in related context |
| 369 | if not rel: |
| 370 | return None |
| 371 | return Field.get_manipulator_new_data(self, new_data, rel) |
| 372 | |
| 373 | def contribute_to_class(self, cls, name): |
| 374 | assert not cls._meta.has_auto_field, "A model can't have more than one AutoField." |
| 375 | super(AutoField, self).contribute_to_class(cls, name) |
| 376 | cls._meta.has_auto_field = True |
| 377 | |
| 378 | def formfield(self): |
| 379 | return None |
| 380 | |
| 381 | class BooleanField(Field): |
| 382 | def __init__(self, *args, **kwargs): |
| 383 | kwargs['blank'] = True |
| 384 | Field.__init__(self, *args, **kwargs) |
| 385 | |
| 386 | def to_python(self, value): |
| 387 | if value in (True, False): return value |
| 388 | if value in ('t', 'True', '1'): return True |
| 389 | if value in ('f', 'False', '0'): return False |
| 390 | raise validators.ValidationError, gettext("This value must be either True or False.") |
| 391 | |
| 392 | def get_manipulator_field_objs(self): |
| 393 | return [oldforms.CheckboxField] |
| 394 | |
| 395 | def formfield(self): |
| 396 | return forms.BooleanField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 397 | |
| 398 | class CharField(Field): |
| 399 | def get_manipulator_field_objs(self): |
| 400 | return [oldforms.TextField] |
| 401 | |
| 402 | def to_python(self, value): |
| 403 | if isinstance(value, basestring): |
| 404 | return value |
| 405 | if value is None: |
| 406 | if self.null: |
| 407 | return value |
| 408 | else: |
| 409 | raise validators.ValidationError, gettext_lazy("This field cannot be null.") |
| 410 | return str(value) |
| 411 | |
| 412 | def formfield(self): |
| 413 | return forms.CharField(max_length=self.maxlength, required=not self.blank, label=capfirst(self.verbose_name)) |
| 414 | |
| 415 | # TODO: Maybe move this into contrib, because it's specialized. |
| 416 | class CommaSeparatedIntegerField(CharField): |
| 417 | def get_manipulator_field_objs(self): |
| 418 | return [oldforms.CommaSeparatedIntegerField] |
| 419 | |
| 420 | class DateField(Field): |
| 421 | empty_strings_allowed = False |
| 422 | def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
| 423 | self.auto_now, self.auto_now_add = auto_now, auto_now_add |
| 424 | #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. |
| 425 | if auto_now or auto_now_add: |
| 426 | kwargs['editable'] = False |
| 427 | kwargs['blank'] = True |
| 428 | Field.__init__(self, verbose_name, name, **kwargs) |
| 429 | |
| 430 | def to_python(self, value): |
| 431 | if isinstance(value, datetime.datetime): |
| 432 | return value.date() |
| 433 | if isinstance(value, datetime.date): |
| 434 | return value |
| 435 | validators.isValidANSIDate(value, None) |
| 436 | try: |
| 437 | return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3]) |
| 438 | except ValueError: |
| 439 | raise validators.ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.') |
| 440 | |
| 441 | def get_db_prep_lookup(self, lookup_type, value): |
| 442 | if lookup_type == 'range': |
| 443 | value = [str(v) for v in value] |
| 444 | elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte') and hasattr(value, 'strftime'): |
| 445 | value = value.strftime('%Y-%m-%d') |
| 446 | else: |
| 447 | value = str(value) |
| 448 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 449 | |
| 450 | def pre_save(self, model_instance, add): |
| 451 | if self.auto_now or (self.auto_now_add and add): |
| 452 | value = datetime.datetime.now() |
| 453 | setattr(model_instance, self.attname, value) |
| 454 | return value |
| 455 | else: |
| 456 | return super(DateField, self).pre_save(model_instance, add) |
| 457 | |
| 458 | def contribute_to_class(self, cls, name): |
| 459 | super(DateField,self).contribute_to_class(cls, name) |
| 460 | if not self.null: |
| 461 | setattr(cls, 'get_next_by_%s' % self.name, |
| 462 | curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) |
| 463 | setattr(cls, 'get_previous_by_%s' % self.name, |
| 464 | curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) |
| 465 | |
| 466 | # Needed because of horrible auto_now[_add] behaviour wrt. editable |
| 467 | def get_follow(self, override=None): |
| 468 | if override != None: |
| 469 | return override |
| 470 | else: |
| 471 | return self.editable or self.auto_now or self.auto_now_add |
| 472 | |
| 473 | def get_db_prep_save(self, value): |
| 474 | # Casts dates into string format for entry into database. |
| 475 | if value is not None: |
| 476 | value = value.strftime('%Y-%m-%d') |
| 477 | return Field.get_db_prep_save(self, value) |
| 478 | |
| 479 | def get_manipulator_field_objs(self): |
| 480 | return [oldforms.DateField] |
| 481 | |
| 482 | def flatten_data(self, follow, obj = None): |
| 483 | val = self._get_val_from_obj(obj) |
| 484 | return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')} |
| 485 | |
| 486 | def formfield(self): |
| 487 | return forms.DateField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 488 | |
| 489 | class DateTimeField(DateField): |
| 490 | def to_python(self, value): |
| 491 | if isinstance(value, datetime.datetime): |
| 492 | return value |
| 493 | if isinstance(value, datetime.date): |
| 494 | return datetime.datetime(value.year, value.month, value.day) |
| 495 | try: # Seconds are optional, so try converting seconds first. |
| 496 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6]) |
| 497 | except ValueError: |
| 498 | try: # Try without seconds. |
| 499 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5]) |
| 500 | except ValueError: # Try without hour/minutes/seconds. |
| 501 | try: |
| 502 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3]) |
| 503 | except ValueError: |
| 504 | raise validators.ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') |
| 505 | |
| 506 | def get_db_prep_save(self, value): |
| 507 | # Casts dates into string format for entry into database. |
| 508 | if value is not None: |
| 509 | # MySQL will throw a warning if microseconds are given, because it |
| 510 | # doesn't support microseconds. |
| 511 | if (settings.DATABASE_ENGINE == 'mysql' or settings.DATABASE_ENGINE == 'ado_mssql') and hasattr(value, 'microsecond'): |
| 512 | value = value.replace(microsecond=0) |
| 513 | value = str(value) |
| 514 | return Field.get_db_prep_save(self, value) |
| 515 | |
| 516 | def get_db_prep_lookup(self, lookup_type, value): |
| 517 | # MSSQL doesn't like microseconds. |
| 518 | if settings.DATABASE_ENGINE == 'ado_mssql' and hasattr(value, 'microsecond'): |
| 519 | value = value.replace(microsecond=0) |
| 520 | if lookup_type == 'range': |
| 521 | value = [str(v) for v in value] |
| 522 | else: |
| 523 | value = str(value) |
| 524 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 525 | |
| 526 | def get_manipulator_field_objs(self): |
| 527 | return [oldforms.DateField, oldforms.TimeField] |
| 528 | |
| 529 | def get_manipulator_field_names(self, name_prefix): |
| 530 | return [name_prefix + self.name + '_date', name_prefix + self.name + '_time'] |
| 531 | |
| 532 | def get_manipulator_new_data(self, new_data, rel=False): |
| 533 | date_field, time_field = self.get_manipulator_field_names('') |
| 534 | if rel: |
| 535 | d = new_data.get(date_field, [None])[0] |
| 536 | t = new_data.get(time_field, [None])[0] |
| 537 | else: |
| 538 | d = new_data.get(date_field, None) |
| 539 | t = new_data.get(time_field, None) |
| 540 | if d is not None and t is not None: |
| 541 | return datetime.datetime.combine(d, t) |
| 542 | return self.get_default() |
| 543 | |
| 544 | def flatten_data(self,follow, obj = None): |
| 545 | val = self._get_val_from_obj(obj) |
| 546 | date_field, time_field = self.get_manipulator_field_names('') |
| 547 | return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''), |
| 548 | time_field: (val is not None and val.strftime("%H:%M:%S") or '')} |
| 549 | |
| 550 | def formfield(self): |
| 551 | return forms.DateTimeField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 552 | |
| 553 | class EmailField(CharField): |
| 554 | def __init__(self, *args, **kwargs): |
| 555 | kwargs['maxlength'] = 75 |
| 556 | CharField.__init__(self, *args, **kwargs) |
| 557 | |
| 558 | def get_internal_type(self): |
| 559 | return "CharField" |
| 560 | |
| 561 | def get_manipulator_field_objs(self): |
| 562 | return [oldforms.EmailField] |
| 563 | |
| 564 | def validate(self, field_data, all_data): |
| 565 | validators.isValidEmail(field_data, all_data) |
| 566 | |
| 567 | def formfield(self): |
| 568 | return forms.EmailField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 569 | |
| 570 | class FileField(Field): |
| 571 | def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs): |
| 572 | self.upload_to = upload_to |
| 573 | Field.__init__(self, verbose_name, name, **kwargs) |
| 574 | |
| 575 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 576 | field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
| 577 | if not self.blank: |
| 578 | if rel: |
| 579 | # This validator makes sure FileFields work in a related context. |
| 580 | class RequiredFileField(object): |
| 581 | def __init__(self, other_field_names, other_file_field_name): |
| 582 | self.other_field_names = other_field_names |
| 583 | self.other_file_field_name = other_file_field_name |
| 584 | self.always_test = True |
| 585 | def __call__(self, field_data, all_data): |
| 586 | if not all_data.get(self.other_file_field_name, False): |
| 587 | c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, gettext_lazy("This field is required.")) |
| 588 | c(field_data, all_data) |
| 589 | # First, get the core fields, if any. |
| 590 | core_field_names = [] |
| 591 | for f in opts.fields: |
| 592 | if f.core and f != self: |
| 593 | core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
| 594 | # Now, if there are any, add the validator to this FormField. |
| 595 | if core_field_names: |
| 596 | field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) |
| 597 | else: |
| 598 | v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, gettext_lazy("This field is required.")) |
| 599 | v.always_test = True |
| 600 | field_list[0].validator_list.append(v) |
| 601 | field_list[0].is_required = field_list[1].is_required = False |
| 602 | |
| 603 | # If the raw path is passed in, validate it's under the MEDIA_ROOT. |
| 604 | def isWithinMediaRoot(field_data, all_data): |
| 605 | f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data)) |
| 606 | if not f.startswith(os.path.abspath(os.path.normpath(settings.MEDIA_ROOT))): |
| 607 | raise validators.ValidationError, _("Enter a valid filename.") |
| 608 | field_list[1].validator_list.append(isWithinMediaRoot) |
| 609 | return field_list |
| 610 | |
| 611 | def contribute_to_class(self, cls, name): |
| 612 | super(FileField, self).contribute_to_class(cls, name) |
| 613 | setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self)) |
| 614 | setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self)) |
| 615 | setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self)) |
| 616 | setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents: instance._save_FIELD_file(self, filename, raw_contents)) |
| 617 | dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls) |
| 618 | |
| 619 | def delete_file(self, instance): |
| 620 | if getattr(instance, self.attname): |
| 621 | file_name = getattr(instance, 'get_%s_filename' % self.name)() |
| 622 | # If the file exists and no other object of this type references it, |
| 623 | # delete it from the filesystem. |
| 624 | if os.path.exists(file_name) and \ |
| 625 | not instance.__class__._default_manager.filter(**{'%s__exact' % self.name: getattr(instance, self.attname)}): |
| 626 | os.remove(file_name) |
| 627 | |
| 628 | def get_manipulator_field_objs(self): |
| 629 | return [oldforms.FileUploadField, oldforms.HiddenField] |
| 630 | |
| 631 | def get_manipulator_field_names(self, name_prefix): |
| 632 | return [name_prefix + self.name + '_file', name_prefix + self.name] |
| 633 | |
| 634 | def save_file(self, new_data, new_object, original_object, change, rel): |
| 635 | upload_field_name = self.get_manipulator_field_names('')[0] |
| 636 | if new_data.get(upload_field_name, False): |
| 637 | func = getattr(new_object, 'save_%s_file' % self.name) |
| 638 | if rel: |
| 639 | func(new_data[upload_field_name][0]["filename"], new_data[upload_field_name][0]["content"]) |
| 640 | else: |
| 641 | func(new_data[upload_field_name]["filename"], new_data[upload_field_name]["content"]) |
| 642 | |
| 643 | def get_directory_name(self): |
| 644 | return os.path.normpath(datetime.datetime.now().strftime(self.upload_to)) |
| 645 | |
| 646 | def get_filename(self, filename): |
| 647 | from django.utils.text import get_valid_filename |
| 648 | f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename))) |
| 649 | return os.path.normpath(f) |
| 650 | |
| 651 | class FilePathField(Field): |
| 652 | def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): |
| 653 | self.path, self.match, self.recursive = path, match, recursive |
| 654 | Field.__init__(self, verbose_name, name, **kwargs) |
| 655 | |
| 656 | def get_manipulator_field_objs(self): |
| 657 | return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)] |
| 658 | |
| 659 | class FloatField(Field): |
| 660 | empty_strings_allowed = False |
| 661 | def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): |
| 662 | self.max_digits, self.decimal_places = max_digits, decimal_places |
| 663 | Field.__init__(self, verbose_name, name, **kwargs) |
| 664 | |
| 665 | def get_manipulator_field_objs(self): |
| 666 | return [curry(oldforms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)] |
| 667 | |
| 668 | class ImageField(FileField): |
| 669 | def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): |
| 670 | self.width_field, self.height_field = width_field, height_field |
| 671 | FileField.__init__(self, verbose_name, name, **kwargs) |
| 672 | |
| 673 | def get_manipulator_field_objs(self): |
| 674 | return [oldforms.ImageUploadField, oldforms.HiddenField] |
| 675 | |
| 676 | def contribute_to_class(self, cls, name): |
| 677 | super(ImageField, self).contribute_to_class(cls, name) |
| 678 | # Add get_BLAH_width and get_BLAH_height methods, but only if the |
| 679 | # image field doesn't have width and height cache fields. |
| 680 | if not self.width_field: |
| 681 | setattr(cls, 'get_%s_width' % self.name, curry(cls._get_FIELD_width, field=self)) |
| 682 | if not self.height_field: |
| 683 | setattr(cls, 'get_%s_height' % self.name, curry(cls._get_FIELD_height, field=self)) |
| 684 | |
| 685 | def save_file(self, new_data, new_object, original_object, change, rel): |
| 686 | FileField.save_file(self, new_data, new_object, original_object, change, rel) |
| 687 | # If the image has height and/or width field(s) and they haven't |
| 688 | # changed, set the width and/or height field(s) back to their original |
| 689 | # values. |
| 690 | if change and (self.width_field or self.height_field): |
| 691 | if self.width_field: |
| 692 | setattr(new_object, self.width_field, getattr(original_object, self.width_field)) |
| 693 | if self.height_field: |
| 694 | setattr(new_object, self.height_field, getattr(original_object, self.height_field)) |
| 695 | new_object.save() |
| 696 | |
| 697 | class IntegerField(Field): |
| 698 | empty_strings_allowed = False |
| 699 | def get_manipulator_field_objs(self): |
| 700 | return [oldforms.IntegerField] |
| 701 | |
| 702 | def formfield(self): |
| 703 | return forms.IntegerField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 704 | |
| 705 | class IPAddressField(Field): |
| 706 | def __init__(self, *args, **kwargs): |
| 707 | kwargs['maxlength'] = 15 |
| 708 | Field.__init__(self, *args, **kwargs) |
| 709 | |
| 710 | def get_manipulator_field_objs(self): |
| 711 | return [oldforms.IPAddressField] |
| 712 | |
| 713 | def validate(self, field_data, all_data): |
| 714 | validators.isValidIPAddress4(field_data, None) |
| 715 | |
| 716 | class NullBooleanField(Field): |
| 717 | def __init__(self, *args, **kwargs): |
| 718 | kwargs['null'] = True |
| 719 | Field.__init__(self, *args, **kwargs) |
| 720 | |
| 721 | def get_manipulator_field_objs(self): |
| 722 | return [oldforms.NullBooleanField] |
| 723 | |
| 724 | class PhoneNumberField(IntegerField): |
| 725 | def get_manipulator_field_objs(self): |
| 726 | return [oldforms.PhoneNumberField] |
| 727 | |
| 728 | def validate(self, field_data, all_data): |
| 729 | validators.isValidPhone(field_data, all_data) |
| 730 | |
| 731 | class PositiveIntegerField(IntegerField): |
| 732 | def get_manipulator_field_objs(self): |
| 733 | return [oldforms.PositiveIntegerField] |
| 734 | |
| 735 | class PositiveSmallIntegerField(IntegerField): |
| 736 | def get_manipulator_field_objs(self): |
| 737 | return [oldforms.PositiveSmallIntegerField] |
| 738 | |
| 739 | class SlugField(Field): |
| 740 | def __init__(self, *args, **kwargs): |
| 741 | kwargs['maxlength'] = kwargs.get('maxlength', 50) |
| 742 | kwargs.setdefault('validator_list', []).append(validators.isSlug) |
| 743 | # Set db_index=True unless it's been set manually. |
| 744 | if not kwargs.has_key('db_index'): |
| 745 | kwargs['db_index'] = True |
| 746 | Field.__init__(self, *args, **kwargs) |
| 747 | |
| 748 | def get_manipulator_field_objs(self): |
| 749 | return [oldforms.TextField] |
| 750 | |
| 751 | class SmallIntegerField(IntegerField): |
| 752 | def get_manipulator_field_objs(self): |
| 753 | return [oldforms.SmallIntegerField] |
| 754 | |
| 755 | class TextField(Field): |
| 756 | def get_manipulator_field_objs(self): |
| 757 | return [oldforms.LargeTextField] |
| 758 | |
| 759 | class TimeField(Field): |
| 760 | empty_strings_allowed = False |
| 761 | def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
| 762 | self.auto_now, self.auto_now_add = auto_now, auto_now_add |
| 763 | if auto_now or auto_now_add: |
| 764 | kwargs['editable'] = False |
| 765 | Field.__init__(self, verbose_name, name, **kwargs) |
| 766 | |
| 767 | def get_db_prep_lookup(self, lookup_type, value): |
| 768 | if lookup_type == 'range': |
| 769 | value = [str(v) for v in value] |
| 770 | else: |
| 771 | value = str(value) |
| 772 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 773 | |
| 774 | def pre_save(self, model_instance, add): |
| 775 | if self.auto_now or (self.auto_now_add and add): |
| 776 | value = datetime.datetime.now().time() |
| 777 | setattr(model_instance, self.attname, value) |
| 778 | return value |
| 779 | else: |
| 780 | return super(TimeField, self).pre_save(model_instance, add) |
| 781 | |
| 782 | def get_db_prep_save(self, value): |
| 783 | # Casts dates into string format for entry into database. |
| 784 | if value is not None: |
| 785 | # MySQL will throw a warning if microseconds are given, because it |
| 786 | # doesn't support microseconds. |
| 787 | if settings.DATABASE_ENGINE == 'mysql' or settings.DATABASE_ENGINE == 'ado_mssql': |
| 788 | value = value.replace(microsecond=0) |
| 789 | value = str(value) |
| 790 | return Field.get_db_prep_save(self, value) |
| 791 | |
| 792 | def get_manipulator_field_objs(self): |
| 793 | return [oldforms.TimeField] |
| 794 | |
| 795 | def flatten_data(self,follow, obj = None): |
| 796 | val = self._get_val_from_obj(obj) |
| 797 | return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')} |
| 798 | |
| 799 | def formfield(self): |
| 800 | return forms.TimeField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 801 | |
| 802 | class URLField(Field): |
| 803 | def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): |
| 804 | if verify_exists: |
| 805 | kwargs.setdefault('validator_list', []).append(validators.isExistingURL) |
| 806 | self.verify_exists = verify_exists |
| 807 | Field.__init__(self, verbose_name, name, **kwargs) |
| 808 | |
| 809 | def get_manipulator_field_objs(self): |
| 810 | return [oldforms.URLField] |
| 811 | |
| 812 | def formfield(self): |
| 813 | return forms.URLField(required=not self.blank, verify_exists=self.verify_exists, label=capfirst(self.verbose_name)) |
| 814 | |
| 815 | class USStateField(Field): |
| 816 | def get_manipulator_field_objs(self): |
| 817 | return [oldforms.USStateField] |
| 818 | |
| 819 | class XMLField(TextField): |
| 820 | def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): |
| 821 | self.schema_path = schema_path |
| 822 | Field.__init__(self, verbose_name, name, **kwargs) |
| 823 | |
| 824 | def get_internal_type(self): |
| 825 | return "TextField" |
| 826 | |
| 827 | def get_manipulator_field_objs(self): |
| 828 | return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)] |
| 829 | |
| 830 | class OrderingField(IntegerField): |
| 831 | empty_strings_allowed=False |
| 832 | def __init__(self, with_respect_to, **kwargs): |
| 833 | self.wrt = with_respect_to |
| 834 | kwargs['null'] = True |
| 835 | IntegerField.__init__(self, **kwargs ) |
| 836 | |
| 837 | def get_internal_type(self): |
| 838 | return "IntegerField" |
| 839 | |
| 840 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 841 | return [oldforms.HiddenField(name_prefix + self.name)] |
| 842 | from django.db.models import signals |
| 843 | from django.dispatch import dispatcher |
| 844 | from django.conf import settings |
| 845 | from django.core import validators |
| 846 | from django import oldforms |
| 847 | from django import newforms as forms |
| 848 | from django.core.exceptions import ObjectDoesNotExist |
| 849 | from django.utils.functional import curry |
| 850 | from django.utils.itercompat import tee |
| 851 | from django.utils.text import capfirst |
| 852 | from django.utils.translation import gettext, gettext_lazy |
| 853 | import datetime, os, time |
| 854 | |
| 855 | class NOT_PROVIDED: |
| 856 | pass |
| 857 | |
| 858 | # Values for filter_interface. |
| 859 | HORIZONTAL, VERTICAL = 1, 2 |
| 860 | |
| 861 | # The values to use for "blank" in SelectFields. Will be appended to the start of most "choices" lists. |
| 862 | BLANK_CHOICE_DASH = [("", "---------")] |
| 863 | BLANK_CHOICE_NONE = [("", "None")] |
| 864 | |
| 865 | # prepares a value for use in a LIKE query |
| 866 | prep_for_like_query = lambda x: str(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") |
| 867 | |
| 868 | # returns the <ul> class for a given radio_admin value |
| 869 | get_ul_class = lambda x: 'radiolist%s' % ((x == HORIZONTAL) and ' inline' or '') |
| 870 | |
| 871 | class FieldDoesNotExist(Exception): |
| 872 | pass |
| 873 | |
| 874 | def manipulator_validator_unique(f, opts, self, field_data, all_data): |
| 875 | "Validates that the value is unique for this field." |
| 876 | lookup_type = f.get_validator_unique_lookup_type() |
| 877 | try: |
| 878 | old_obj = self.manager.get(**{lookup_type: field_data}) |
| 879 | except ObjectDoesNotExist: |
| 880 | return |
| 881 | if getattr(self, 'original_object', None) and self.original_object._get_pk_val() == old_obj._get_pk_val(): |
| 882 | return |
| 883 | raise validators.ValidationError, gettext("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name} |
| 884 | |
| 885 | # A guide to Field parameters: |
| 886 | # |
| 887 | # * name: The name of the field specifed in the model. |
| 888 | # * attname: The attribute to use on the model object. This is the same as |
| 889 | # "name", except in the case of ForeignKeys, where "_id" is |
| 890 | # appended. |
| 891 | # * db_column: The db_column specified in the model (or None). |
| 892 | # * column: The database column for this field. This is the same as |
| 893 | # "attname", except if db_column is specified. |
| 894 | # |
| 895 | # Code that introspects values, or does other dynamic things, should use |
| 896 | # attname. For example, this gets the primary key value of object "obj": |
| 897 | # |
| 898 | # getattr(obj, opts.pk.attname) |
| 899 | |
| 900 | class Field(object): |
| 901 | |
| 902 | # Designates whether empty strings fundamentally are allowed at the |
| 903 | # database level. |
| 904 | empty_strings_allowed = True |
| 905 | |
| 906 | # Tracks each time a Field instance is created. Used to retain order. |
| 907 | creation_counter = 0 |
| 908 | |
| 909 | def __init__(self, verbose_name=None, name=None, primary_key=False, |
| 910 | maxlength=None, unique=False, blank=False, null=False, db_index=False, |
| 911 | core=False, rel=None, default=NOT_PROVIDED, editable=True, |
| 912 | prepopulate_from=None, unique_for_date=None, unique_for_month=None, |
| 913 | unique_for_year=None, validator_list=None, choices=None, radio_admin=None, |
| 914 | help_text='', db_column=None): |
| 915 | self.name = name |
| 916 | self.verbose_name = verbose_name |
| 917 | self.primary_key = primary_key |
| 918 | self.maxlength, self.unique = maxlength, unique |
| 919 | self.blank, self.null = blank, null |
| 920 | self.core, self.rel, self.default = core, rel, default |
| 921 | self.editable = editable |
| 922 | self.validator_list = validator_list or [] |
| 923 | self.prepopulate_from = prepopulate_from |
| 924 | self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month |
| 925 | self.unique_for_year = unique_for_year |
| 926 | self._choices = choices or [] |
| 927 | self.radio_admin = radio_admin |
| 928 | self.help_text = help_text |
| 929 | self.db_column = db_column |
| 930 | |
| 931 | # Set db_index to True if the field has a relationship and doesn't explicitly set db_index. |
| 932 | self.db_index = db_index |
| 933 | |
| 934 | # Increase the creation counter, and save our local copy. |
| 935 | self.creation_counter = Field.creation_counter |
| 936 | Field.creation_counter += 1 |
| 937 | |
| 938 | def __cmp__(self, other): |
| 939 | # This is needed because bisect does not take a comparison function. |
| 940 | return cmp(self.creation_counter, other.creation_counter) |
| 941 | |
| 942 | def to_python(self, value): |
| 943 | """ |
| 944 | Converts the input value into the expected Python data type, raising |
| 945 | validators.ValidationError if the data can't be converted. Returns the |
| 946 | converted value. Subclasses should override this. |
| 947 | """ |
| 948 | return value |
| 949 | |
| 950 | def validate_full(self, field_data, all_data): |
| 951 | """ |
| 952 | Returns a list of errors for this field. This is the main interface, |
| 953 | as it encapsulates some basic validation logic used by all fields. |
| 954 | Subclasses should implement validate(), not validate_full(). |
| 955 | """ |
| 956 | if not self.blank and not field_data: |
| 957 | return [gettext_lazy('This field is required.')] |
| 958 | try: |
| 959 | self.validate(field_data, all_data) |
| 960 | except validators.ValidationError, e: |
| 961 | return e.messages |
| 962 | return [] |
| 963 | |
| 964 | def validate(self, field_data, all_data): |
| 965 | """ |
| 966 | Raises validators.ValidationError if field_data has any errors. |
| 967 | Subclasses should override this to specify field-specific validation |
| 968 | logic. This method should assume field_data has already been converted |
| 969 | into the appropriate data type by Field.to_python(). |
| 970 | """ |
| 971 | pass |
| 972 | |
| 973 | def set_attributes_from_name(self, name): |
| 974 | self.name = name |
| 975 | self.attname, self.column = self.get_attname_column() |
| 976 | self.verbose_name = self.verbose_name or (name and name.replace('_', ' ')) |
| 977 | |
| 978 | def contribute_to_class(self, cls, name): |
| 979 | self.set_attributes_from_name(name) |
| 980 | cls._meta.add_field(self) |
| 981 | if self.choices: |
| 982 | setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) |
| 983 | |
| 984 | def get_attname(self): |
| 985 | return self.name |
| 986 | |
| 987 | def get_attname_column(self): |
| 988 | attname = self.get_attname() |
| 989 | column = self.db_column or attname |
| 990 | return attname, column |
| 991 | |
| 992 | def get_cache_name(self): |
| 993 | return '_%s_cache' % self.name |
| 994 | |
| 995 | def get_internal_type(self): |
| 996 | return self.__class__.__name__ |
| 997 | |
| 998 | def pre_save(self, model_instance, add): |
| 999 | "Returns field's value just before saving." |
| 1000 | return getattr(model_instance, self.attname) |
| 1001 | |
| 1002 | def get_db_prep_save(self, value): |
| 1003 | "Returns field's value prepared for saving into a database." |
| 1004 | return value |
| 1005 | |
| 1006 | def get_db_prep_lookup(self, lookup_type, value): |
| 1007 | "Returns field's value prepared for database lookup." |
| 1008 | if lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte', 'year', 'month', 'day', 'search'): |
| 1009 | return [value] |
| 1010 | elif lookup_type in ('range', 'in'): |
| 1011 | return value |
| 1012 | elif lookup_type in ('contains', 'icontains'): |
| 1013 | return ["%%%s%%" % prep_for_like_query(value)] |
| 1014 | elif lookup_type == 'iexact': |
| 1015 | return [prep_for_like_query(value)] |
| 1016 | elif lookup_type in ('startswith', 'istartswith'): |
| 1017 | return ["%s%%" % prep_for_like_query(value)] |
| 1018 | elif lookup_type in ('endswith', 'iendswith'): |
| 1019 | return ["%%%s" % prep_for_like_query(value)] |
| 1020 | elif lookup_type == 'isnull': |
| 1021 | return [] |
| 1022 | raise TypeError, "Field has invalid lookup: %s" % lookup_type |
| 1023 | |
| 1024 | def has_default(self): |
| 1025 | "Returns a boolean of whether this field has a default value." |
| 1026 | return self.default is not NOT_PROVIDED |
| 1027 | |
| 1028 | def get_default(self): |
| 1029 | "Returns the default value for this field." |
| 1030 | if self.default is not NOT_PROVIDED: |
| 1031 | if callable(self.default): |
| 1032 | return self.default() |
| 1033 | return self.default |
| 1034 | if not self.empty_strings_allowed or self.null: |
| 1035 | return None |
| 1036 | return "" |
| 1037 | |
| 1038 | def get_manipulator_field_names(self, name_prefix): |
| 1039 | """ |
| 1040 | Returns a list of field names that this object adds to the manipulator. |
| 1041 | """ |
| 1042 | return [name_prefix + self.name] |
| 1043 | |
| 1044 | def prepare_field_objs_and_params(self, manipulator, name_prefix): |
| 1045 | params = {'validator_list': self.validator_list[:]} |
| 1046 | if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter. |
| 1047 | params['maxlength'] = self.maxlength |
| 1048 | |
| 1049 | if self.choices: |
| 1050 | if self.radio_admin: |
| 1051 | field_objs = [oldforms.RadioSelectField] |
| 1052 | params['ul_class'] = get_ul_class(self.radio_admin) |
| 1053 | else: |
| 1054 | field_objs = [oldforms.SelectField] |
| 1055 | |
| 1056 | params['choices'] = self.get_choices_default() |
| 1057 | else: |
| 1058 | field_objs = self.get_manipulator_field_objs() |
| 1059 | return (field_objs, params) |
| 1060 | |
| 1061 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 1062 | """ |
| 1063 | Returns a list of oldforms.FormField instances for this field. It |
| 1064 | calculates the choices at runtime, not at compile time. |
| 1065 | |
| 1066 | name_prefix is a prefix to prepend to the "field_name" argument. |
| 1067 | rel is a boolean specifying whether this field is in a related context. |
| 1068 | """ |
| 1069 | field_objs, params = self.prepare_field_objs_and_params(manipulator, name_prefix) |
| 1070 | |
| 1071 | # Add the "unique" validator(s). |
| 1072 | for field_name_list in opts.unique_together: |
| 1073 | if field_name_list[0] == self.name: |
| 1074 | params['validator_list'].append(getattr(manipulator, 'isUnique%s' % '_'.join(field_name_list))) |
| 1075 | |
| 1076 | # Add the "unique for..." validator(s). |
| 1077 | if self.unique_for_date: |
| 1078 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_date))) |
| 1079 | if self.unique_for_month: |
| 1080 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_month))) |
| 1081 | if self.unique_for_year: |
| 1082 | params['validator_list'].append(getattr(manipulator, 'isUnique%sFor%s' % (self.name, self.unique_for_year))) |
| 1083 | if self.unique or (self.primary_key and not rel): |
| 1084 | params['validator_list'].append(curry(manipulator_validator_unique, self, opts, manipulator)) |
| 1085 | |
| 1086 | # Only add is_required=True if the field cannot be blank. Primary keys |
| 1087 | # are a special case, and fields in a related context should set this |
| 1088 | # as False, because they'll be caught by a separate validator -- |
| 1089 | # RequiredIfOtherFieldGiven. |
| 1090 | params['is_required'] = not self.blank and not self.primary_key and not rel |
| 1091 | |
| 1092 | # BooleanFields (CheckboxFields) are a special case. They don't take |
| 1093 | # is_required. |
| 1094 | if isinstance(self, BooleanField): |
| 1095 | del params['is_required'] |
| 1096 | |
| 1097 | # If this field is in a related context, check whether any other fields |
| 1098 | # in the related object have core=True. If so, add a validator -- |
| 1099 | # RequiredIfOtherFieldsGiven -- to this FormField. |
| 1100 | if rel and not self.blank and not isinstance(self, AutoField) and not isinstance(self, FileField): |
| 1101 | # First, get the core fields, if any. |
| 1102 | core_field_names = [] |
| 1103 | for f in opts.fields: |
| 1104 | if f.core and f != self: |
| 1105 | core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
| 1106 | # Now, if there are any, add the validator to this FormField. |
| 1107 | if core_field_names: |
| 1108 | params['validator_list'].append(validators.RequiredIfOtherFieldsGiven(core_field_names, gettext_lazy("This field is required."))) |
| 1109 | |
| 1110 | # Finally, add the field_names. |
| 1111 | field_names = self.get_manipulator_field_names(name_prefix) |
| 1112 | return [man(field_name=field_names[i], **params) for i, man in enumerate(field_objs)] |
| 1113 | |
| 1114 | def get_validator_unique_lookup_type(self): |
| 1115 | return '%s__exact' % self.name |
| 1116 | |
| 1117 | def get_manipulator_new_data(self, new_data, rel=False): |
| 1118 | """ |
| 1119 | Given the full new_data dictionary (from the manipulator), returns this |
| 1120 | field's data. |
| 1121 | """ |
| 1122 | if rel: |
| 1123 | return new_data.get(self.name, [self.get_default()])[0] |
| 1124 | val = new_data.get(self.name, self.get_default()) |
| 1125 | if not self.empty_strings_allowed and val == '' and self.null: |
| 1126 | val = None |
| 1127 | return val |
| 1128 | |
| 1129 | def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): |
| 1130 | "Returns a list of tuples used as SelectField choices for this field." |
| 1131 | first_choice = include_blank and blank_choice or [] |
| 1132 | if self.choices: |
| 1133 | return first_choice + list(self.choices) |
| 1134 | rel_model = self.rel.to |
| 1135 | if hasattr(self.rel, 'get_related_field'): |
| 1136 | lst = [(getattr(x, self.rel.get_related_field().attname), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
| 1137 | else: |
| 1138 | lst = [(x._get_pk_val(), str(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
| 1139 | return first_choice + lst |
| 1140 | |
| 1141 | def get_choices_default(self): |
| 1142 | if self.radio_admin: |
| 1143 | return self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE) |
| 1144 | else: |
| 1145 | return self.get_choices() |
| 1146 | |
| 1147 | def _get_val_from_obj(self, obj): |
| 1148 | if obj: |
| 1149 | return getattr(obj, self.attname) |
| 1150 | else: |
| 1151 | return self.get_default() |
| 1152 | |
| 1153 | def flatten_data(self, follow, obj=None): |
| 1154 | """ |
| 1155 | Returns a dictionary mapping the field's manipulator field names to its |
| 1156 | "flattened" string values for the admin view. obj is the instance to |
| 1157 | extract the values from. |
| 1158 | """ |
| 1159 | return {self.attname: self._get_val_from_obj(obj)} |
| 1160 | |
| 1161 | def get_follow(self, override=None): |
| 1162 | if override != None: |
| 1163 | return override |
| 1164 | else: |
| 1165 | return self.editable |
| 1166 | |
| 1167 | def bind(self, fieldmapping, original, bound_field_class): |
| 1168 | return bound_field_class(self, fieldmapping, original) |
| 1169 | |
| 1170 | def _get_choices(self): |
| 1171 | if hasattr(self._choices, 'next'): |
| 1172 | choices, self._choices = tee(self._choices) |
| 1173 | return choices |
| 1174 | else: |
| 1175 | return self._choices |
| 1176 | choices = property(_get_choices) |
| 1177 | |
| 1178 | def formfield(self): |
| 1179 | "Returns a django.newforms.Field instance for this database Field." |
| 1180 | # TODO: This is just a temporary default during development. |
| 1181 | return forms.CharField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1182 | |
| 1183 | class AutoField(Field): |
| 1184 | empty_strings_allowed = False |
| 1185 | def __init__(self, *args, **kwargs): |
| 1186 | assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__ |
| 1187 | kwargs['blank'] = True |
| 1188 | Field.__init__(self, *args, **kwargs) |
| 1189 | |
| 1190 | def to_python(self, value): |
| 1191 | if value is None: |
| 1192 | return value |
| 1193 | try: |
| 1194 | return int(value) |
| 1195 | except (TypeError, ValueError): |
| 1196 | raise validators.ValidationError, gettext("This value must be an integer.") |
| 1197 | |
| 1198 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 1199 | if not rel: |
| 1200 | return [] # Don't add a FormField unless it's in a related context. |
| 1201 | return Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
| 1202 | |
| 1203 | def get_manipulator_field_objs(self): |
| 1204 | return [oldforms.HiddenField] |
| 1205 | |
| 1206 | def get_manipulator_new_data(self, new_data, rel=False): |
| 1207 | # Never going to be called |
| 1208 | # Not in main change pages |
| 1209 | # ignored in related context |
| 1210 | if not rel: |
| 1211 | return None |
| 1212 | return Field.get_manipulator_new_data(self, new_data, rel) |
| 1213 | |
| 1214 | def contribute_to_class(self, cls, name): |
| 1215 | assert not cls._meta.has_auto_field, "A model can't have more than one AutoField." |
| 1216 | super(AutoField, self).contribute_to_class(cls, name) |
| 1217 | cls._meta.has_auto_field = True |
| 1218 | |
| 1219 | def formfield(self): |
| 1220 | return None |
| 1221 | |
| 1222 | class BooleanField(Field): |
| 1223 | def __init__(self, *args, **kwargs): |
| 1224 | kwargs['blank'] = True |
| 1225 | Field.__init__(self, *args, **kwargs) |
| 1226 | |
| 1227 | def to_python(self, value): |
| 1228 | if value in (True, False): return value |
| 1229 | if value in ('t', 'True', '1'): return True |
| 1230 | if value in ('f', 'False', '0'): return False |
| 1231 | raise validators.ValidationError, gettext("This value must be either True or False.") |
| 1232 | |
| 1233 | def get_manipulator_field_objs(self): |
| 1234 | return [oldforms.CheckboxField] |
| 1235 | |
| 1236 | def formfield(self): |
| 1237 | return forms.BooleanField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1238 | |
| 1239 | class CharField(Field): |
| 1240 | def get_manipulator_field_objs(self): |
| 1241 | return [oldforms.TextField] |
| 1242 | |
| 1243 | def to_python(self, value): |
| 1244 | if isinstance(value, basestring): |
| 1245 | return value |
| 1246 | if value is None: |
| 1247 | if self.null: |
| 1248 | return value |
| 1249 | else: |
| 1250 | raise validators.ValidationError, gettext_lazy("This field cannot be null.") |
| 1251 | return str(value) |
| 1252 | |
| 1253 | def formfield(self): |
| 1254 | return forms.CharField(max_length=self.maxlength, required=not self.blank, label=capfirst(self.verbose_name)) |
| 1255 | |
| 1256 | # TODO: Maybe move this into contrib, because it's specialized. |
| 1257 | class CommaSeparatedIntegerField(CharField): |
| 1258 | def get_manipulator_field_objs(self): |
| 1259 | return [oldforms.CommaSeparatedIntegerField] |
| 1260 | |
| 1261 | class DateField(Field): |
| 1262 | empty_strings_allowed = False |
| 1263 | def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
| 1264 | self.auto_now, self.auto_now_add = auto_now, auto_now_add |
| 1265 | #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. |
| 1266 | if auto_now or auto_now_add: |
| 1267 | kwargs['editable'] = False |
| 1268 | kwargs['blank'] = True |
| 1269 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1270 | |
| 1271 | def to_python(self, value): |
| 1272 | if isinstance(value, datetime.datetime): |
| 1273 | return value.date() |
| 1274 | if isinstance(value, datetime.date): |
| 1275 | return value |
| 1276 | validators.isValidANSIDate(value, None) |
| 1277 | try: |
| 1278 | return datetime.date(*time.strptime(value, '%Y-%m-%d')[:3]) |
| 1279 | except ValueError: |
| 1280 | raise validators.ValidationError, gettext('Enter a valid date in YYYY-MM-DD format.') |
| 1281 | |
| 1282 | def get_db_prep_lookup(self, lookup_type, value): |
| 1283 | if lookup_type == 'range': |
| 1284 | value = [str(v) for v in value] |
| 1285 | elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte') and hasattr(value, 'strftime'): |
| 1286 | value = value.strftime('%Y-%m-%d') |
| 1287 | else: |
| 1288 | value = str(value) |
| 1289 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 1290 | |
| 1291 | def pre_save(self, model_instance, add): |
| 1292 | if self.auto_now or (self.auto_now_add and add): |
| 1293 | value = datetime.datetime.now() |
| 1294 | setattr(model_instance, self.attname, value) |
| 1295 | return value |
| 1296 | else: |
| 1297 | return super(DateField, self).pre_save(model_instance, add) |
| 1298 | |
| 1299 | def contribute_to_class(self, cls, name): |
| 1300 | super(DateField,self).contribute_to_class(cls, name) |
| 1301 | if not self.null: |
| 1302 | setattr(cls, 'get_next_by_%s' % self.name, |
| 1303 | curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) |
| 1304 | setattr(cls, 'get_previous_by_%s' % self.name, |
| 1305 | curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) |
| 1306 | |
| 1307 | # Needed because of horrible auto_now[_add] behaviour wrt. editable |
| 1308 | def get_follow(self, override=None): |
| 1309 | if override != None: |
| 1310 | return override |
| 1311 | else: |
| 1312 | return self.editable or self.auto_now or self.auto_now_add |
| 1313 | |
| 1314 | def get_db_prep_save(self, value): |
| 1315 | # Casts dates into string format for entry into database. |
| 1316 | if value is not None: |
| 1317 | value = value.strftime('%Y-%m-%d') |
| 1318 | return Field.get_db_prep_save(self, value) |
| 1319 | |
| 1320 | def get_manipulator_field_objs(self): |
| 1321 | return [oldforms.DateField] |
| 1322 | |
| 1323 | def flatten_data(self, follow, obj = None): |
| 1324 | val = self._get_val_from_obj(obj) |
| 1325 | return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')} |
| 1326 | |
| 1327 | def formfield(self): |
| 1328 | return forms.DateField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1329 | |
| 1330 | class DateTimeField(DateField): |
| 1331 | def to_python(self, value): |
| 1332 | if isinstance(value, datetime.datetime): |
| 1333 | return value |
| 1334 | if isinstance(value, datetime.date): |
| 1335 | return datetime.datetime(value.year, value.month, value.day) |
| 1336 | try: # Seconds are optional, so try converting seconds first. |
| 1337 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6]) |
| 1338 | except ValueError: |
| 1339 | try: # Try without seconds. |
| 1340 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5]) |
| 1341 | except ValueError: # Try without hour/minutes/seconds. |
| 1342 | try: |
| 1343 | return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3]) |
| 1344 | except ValueError: |
| 1345 | raise validators.ValidationError, gettext('Enter a valid date/time in YYYY-MM-DD HH:MM format.') |
| 1346 | |
| 1347 | def get_db_prep_save(self, value): |
| 1348 | # Casts dates into string format for entry into database. |
| 1349 | if value is not None: |
| 1350 | # MySQL will throw a warning if microseconds are given, because it |
| 1351 | # doesn't support microseconds. |
| 1352 | if (settings.DATABASE_ENGINE == 'mysql' or settings.DATABASE_ENGINE == 'ado_mssql') and hasattr(value, 'microsecond'): |
| 1353 | value = value.replace(microsecond=0) |
| 1354 | value = str(value) |
| 1355 | return Field.get_db_prep_save(self, value) |
| 1356 | |
| 1357 | def get_db_prep_lookup(self, lookup_type, value): |
| 1358 | # MSSQL doesn't like microseconds. |
| 1359 | if settings.DATABASE_ENGINE == 'ado_mssql' and hasattr(value, 'microsecond'): |
| 1360 | value = value.replace(microsecond=0) |
| 1361 | if lookup_type == 'range': |
| 1362 | value = [str(v) for v in value] |
| 1363 | else: |
| 1364 | value = str(value) |
| 1365 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 1366 | |
| 1367 | def get_manipulator_field_objs(self): |
| 1368 | return [oldforms.DateField, oldforms.TimeField] |
| 1369 | |
| 1370 | def get_manipulator_field_names(self, name_prefix): |
| 1371 | return [name_prefix + self.name + '_date', name_prefix + self.name + '_time'] |
| 1372 | |
| 1373 | def get_manipulator_new_data(self, new_data, rel=False): |
| 1374 | date_field, time_field = self.get_manipulator_field_names('') |
| 1375 | if rel: |
| 1376 | d = new_data.get(date_field, [None])[0] |
| 1377 | t = new_data.get(time_field, [None])[0] |
| 1378 | else: |
| 1379 | d = new_data.get(date_field, None) |
| 1380 | t = new_data.get(time_field, None) |
| 1381 | if d is not None and t is not None: |
| 1382 | return datetime.datetime.combine(d, t) |
| 1383 | return self.get_default() |
| 1384 | |
| 1385 | def flatten_data(self,follow, obj = None): |
| 1386 | val = self._get_val_from_obj(obj) |
| 1387 | date_field, time_field = self.get_manipulator_field_names('') |
| 1388 | return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''), |
| 1389 | time_field: (val is not None and val.strftime("%H:%M:%S") or '')} |
| 1390 | |
| 1391 | def formfield(self): |
| 1392 | return forms.DateTimeField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1393 | |
| 1394 | class EmailField(CharField): |
| 1395 | def __init__(self, *args, **kwargs): |
| 1396 | kwargs['maxlength'] = 75 |
| 1397 | CharField.__init__(self, *args, **kwargs) |
| 1398 | |
| 1399 | def get_internal_type(self): |
| 1400 | return "CharField" |
| 1401 | |
| 1402 | def get_manipulator_field_objs(self): |
| 1403 | return [oldforms.EmailField] |
| 1404 | |
| 1405 | def validate(self, field_data, all_data): |
| 1406 | validators.isValidEmail(field_data, all_data) |
| 1407 | |
| 1408 | def formfield(self): |
| 1409 | return forms.EmailField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1410 | |
| 1411 | class FileField(Field): |
| 1412 | def __init__(self, verbose_name=None, name=None, upload_to='', **kwargs): |
| 1413 | self.upload_to = upload_to |
| 1414 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1415 | |
| 1416 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 1417 | field_list = Field.get_manipulator_fields(self, opts, manipulator, change, name_prefix, rel, follow) |
| 1418 | if not self.blank: |
| 1419 | if rel: |
| 1420 | # This validator makes sure FileFields work in a related context. |
| 1421 | class RequiredFileField(object): |
| 1422 | def __init__(self, other_field_names, other_file_field_name): |
| 1423 | self.other_field_names = other_field_names |
| 1424 | self.other_file_field_name = other_file_field_name |
| 1425 | self.always_test = True |
| 1426 | def __call__(self, field_data, all_data): |
| 1427 | if not all_data.get(self.other_file_field_name, False): |
| 1428 | c = validators.RequiredIfOtherFieldsGiven(self.other_field_names, gettext_lazy("This field is required.")) |
| 1429 | c(field_data, all_data) |
| 1430 | # First, get the core fields, if any. |
| 1431 | core_field_names = [] |
| 1432 | for f in opts.fields: |
| 1433 | if f.core and f != self: |
| 1434 | core_field_names.extend(f.get_manipulator_field_names(name_prefix)) |
| 1435 | # Now, if there are any, add the validator to this FormField. |
| 1436 | if core_field_names: |
| 1437 | field_list[0].validator_list.append(RequiredFileField(core_field_names, field_list[1].field_name)) |
| 1438 | else: |
| 1439 | v = validators.RequiredIfOtherFieldNotGiven(field_list[1].field_name, gettext_lazy("This field is required.")) |
| 1440 | v.always_test = True |
| 1441 | field_list[0].validator_list.append(v) |
| 1442 | field_list[0].is_required = field_list[1].is_required = False |
| 1443 | |
| 1444 | # If the raw path is passed in, validate it's under the MEDIA_ROOT. |
| 1445 | def isWithinMediaRoot(field_data, all_data): |
| 1446 | f = os.path.abspath(os.path.join(settings.MEDIA_ROOT, field_data)) |
| 1447 | if not f.startswith(os.path.abspath(os.path.normpath(settings.MEDIA_ROOT))): |
| 1448 | raise validators.ValidationError, _("Enter a valid filename.") |
| 1449 | field_list[1].validator_list.append(isWithinMediaRoot) |
| 1450 | return field_list |
| 1451 | |
| 1452 | def contribute_to_class(self, cls, name): |
| 1453 | super(FileField, self).contribute_to_class(cls, name) |
| 1454 | setattr(cls, 'get_%s_filename' % self.name, curry(cls._get_FIELD_filename, field=self)) |
| 1455 | setattr(cls, 'get_%s_url' % self.name, curry(cls._get_FIELD_url, field=self)) |
| 1456 | setattr(cls, 'get_%s_size' % self.name, curry(cls._get_FIELD_size, field=self)) |
| 1457 | setattr(cls, 'save_%s_file' % self.name, lambda instance, filename, raw_contents: instance._save_FIELD_file(self, filename, raw_contents)) |
| 1458 | dispatcher.connect(self.delete_file, signal=signals.post_delete, sender=cls) |
| 1459 | |
| 1460 | def delete_file(self, instance): |
| 1461 | if getattr(instance, self.attname): |
| 1462 | file_name = getattr(instance, 'get_%s_filename' % self.name)() |
| 1463 | # If the file exists and no other object of this type references it, |
| 1464 | # delete it from the filesystem. |
| 1465 | if os.path.exists(file_name) and \ |
| 1466 | not instance.__class__._default_manager.filter(**{'%s__exact' % self.name: getattr(instance, self.attname)}): |
| 1467 | os.remove(file_name) |
| 1468 | |
| 1469 | def get_manipulator_field_objs(self): |
| 1470 | return [oldforms.FileUploadField, oldforms.HiddenField] |
| 1471 | |
| 1472 | def get_manipulator_field_names(self, name_prefix): |
| 1473 | return [name_prefix + self.name + '_file', name_prefix + self.name] |
| 1474 | |
| 1475 | def save_file(self, new_data, new_object, original_object, change, rel): |
| 1476 | upload_field_name = self.get_manipulator_field_names('')[0] |
| 1477 | if new_data.get(upload_field_name, False): |
| 1478 | func = getattr(new_object, 'save_%s_file' % self.name) |
| 1479 | if rel: |
| 1480 | func(new_data[upload_field_name][0]["filename"], new_data[upload_field_name][0]["content"]) |
| 1481 | else: |
| 1482 | func(new_data[upload_field_name]["filename"], new_data[upload_field_name]["content"]) |
| 1483 | |
| 1484 | def get_directory_name(self): |
| 1485 | return os.path.normpath(datetime.datetime.now().strftime(self.upload_to)) |
| 1486 | |
| 1487 | def get_filename(self, filename): |
| 1488 | from django.utils.text import get_valid_filename |
| 1489 | f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename))) |
| 1490 | return os.path.normpath(f) |
| 1491 | |
| 1492 | class FilePathField(Field): |
| 1493 | def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): |
| 1494 | self.path, self.match, self.recursive = path, match, recursive |
| 1495 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1496 | |
| 1497 | def get_manipulator_field_objs(self): |
| 1498 | return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)] |
| 1499 | |
| 1500 | class FloatField(Field): |
| 1501 | empty_strings_allowed = False |
| 1502 | def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): |
| 1503 | self.max_digits, self.decimal_places = max_digits, decimal_places |
| 1504 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1505 | |
| 1506 | def get_manipulator_field_objs(self): |
| 1507 | return [curry(oldforms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)] |
| 1508 | |
| 1509 | class ImageField(FileField): |
| 1510 | def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): |
| 1511 | self.width_field, self.height_field = width_field, height_field |
| 1512 | FileField.__init__(self, verbose_name, name, **kwargs) |
| 1513 | |
| 1514 | def get_manipulator_field_objs(self): |
| 1515 | return [oldforms.ImageUploadField, oldforms.HiddenField] |
| 1516 | |
| 1517 | def contribute_to_class(self, cls, name): |
| 1518 | super(ImageField, self).contribute_to_class(cls, name) |
| 1519 | # Add get_BLAH_width and get_BLAH_height methods, but only if the |
| 1520 | # image field doesn't have width and height cache fields. |
| 1521 | if not self.width_field: |
| 1522 | setattr(cls, 'get_%s_width' % self.name, curry(cls._get_FIELD_width, field=self)) |
| 1523 | if not self.height_field: |
| 1524 | setattr(cls, 'get_%s_height' % self.name, curry(cls._get_FIELD_height, field=self)) |
| 1525 | |
| 1526 | def save_file(self, new_data, new_object, original_object, change, rel): |
| 1527 | FileField.save_file(self, new_data, new_object, original_object, change, rel) |
| 1528 | # If the image has height and/or width field(s) and they haven't |
| 1529 | # changed, set the width and/or height field(s) back to their original |
| 1530 | # values. |
| 1531 | if change and (self.width_field or self.height_field): |
| 1532 | if self.width_field: |
| 1533 | setattr(new_object, self.width_field, getattr(original_object, self.width_field)) |
| 1534 | if self.height_field: |
| 1535 | setattr(new_object, self.height_field, getattr(original_object, self.height_field)) |
| 1536 | new_object.save() |
| 1537 | |
| 1538 | class IntegerField(Field): |
| 1539 | empty_strings_allowed = False |
| 1540 | def get_manipulator_field_objs(self): |
| 1541 | return [oldforms.IntegerField] |
| 1542 | |
| 1543 | def formfield(self): |
| 1544 | return forms.IntegerField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1545 | |
| 1546 | class IPAddressField(Field): |
| 1547 | def __init__(self, *args, **kwargs): |
| 1548 | kwargs['maxlength'] = 15 |
| 1549 | Field.__init__(self, *args, **kwargs) |
| 1550 | |
| 1551 | def get_manipulator_field_objs(self): |
| 1552 | return [oldforms.IPAddressField] |
| 1553 | |
| 1554 | def validate(self, field_data, all_data): |
| 1555 | validators.isValidIPAddress4(field_data, None) |
| 1556 | |
| 1557 | class NullBooleanField(Field): |
| 1558 | def __init__(self, *args, **kwargs): |
| 1559 | kwargs['null'] = True |
| 1560 | Field.__init__(self, *args, **kwargs) |
| 1561 | |
| 1562 | def get_manipulator_field_objs(self): |
| 1563 | return [oldforms.NullBooleanField] |
| 1564 | |
| 1565 | class PhoneNumberField(IntegerField): |
| 1566 | def get_manipulator_field_objs(self): |
| 1567 | return [oldforms.PhoneNumberField] |
| 1568 | |
| 1569 | def validate(self, field_data, all_data): |
| 1570 | validators.isValidPhone(field_data, all_data) |
| 1571 | |
| 1572 | class PositiveIntegerField(IntegerField): |
| 1573 | def get_manipulator_field_objs(self): |
| 1574 | return [oldforms.PositiveIntegerField] |
| 1575 | |
| 1576 | class PositiveSmallIntegerField(IntegerField): |
| 1577 | def get_manipulator_field_objs(self): |
| 1578 | return [oldforms.PositiveSmallIntegerField] |
| 1579 | |
| 1580 | class SlugField(Field): |
| 1581 | def __init__(self, *args, **kwargs): |
| 1582 | kwargs['maxlength'] = kwargs.get('maxlength', 50) |
| 1583 | kwargs.setdefault('validator_list', []).append(validators.isSlug) |
| 1584 | # Set db_index=True unless it's been set manually. |
| 1585 | if not kwargs.has_key('db_index'): |
| 1586 | kwargs['db_index'] = True |
| 1587 | Field.__init__(self, *args, **kwargs) |
| 1588 | |
| 1589 | def get_manipulator_field_objs(self): |
| 1590 | return [oldforms.TextField] |
| 1591 | |
| 1592 | class SmallIntegerField(IntegerField): |
| 1593 | def get_manipulator_field_objs(self): |
| 1594 | return [oldforms.SmallIntegerField] |
| 1595 | |
| 1596 | class TextField(Field): |
| 1597 | def get_manipulator_field_objs(self): |
| 1598 | return [oldforms.LargeTextField] |
| 1599 | |
| 1600 | class TimeField(Field): |
| 1601 | empty_strings_allowed = False |
| 1602 | def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
| 1603 | self.auto_now, self.auto_now_add = auto_now, auto_now_add |
| 1604 | if auto_now or auto_now_add: |
| 1605 | kwargs['editable'] = False |
| 1606 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1607 | |
| 1608 | def get_db_prep_lookup(self, lookup_type, value): |
| 1609 | if lookup_type == 'range': |
| 1610 | value = [str(v) for v in value] |
| 1611 | else: |
| 1612 | value = str(value) |
| 1613 | return Field.get_db_prep_lookup(self, lookup_type, value) |
| 1614 | |
| 1615 | def pre_save(self, model_instance, add): |
| 1616 | if self.auto_now or (self.auto_now_add and add): |
| 1617 | value = datetime.datetime.now().time() |
| 1618 | setattr(model_instance, self.attname, value) |
| 1619 | return value |
| 1620 | else: |
| 1621 | return super(TimeField, self).pre_save(model_instance, add) |
| 1622 | |
| 1623 | def get_db_prep_save(self, value): |
| 1624 | # Casts dates into string format for entry into database. |
| 1625 | if value is not None: |
| 1626 | # MySQL will throw a warning if microseconds are given, because it |
| 1627 | # doesn't support microseconds. |
| 1628 | if settings.DATABASE_ENGINE == 'mysql' or settings.DATABASE_ENGINE == 'ado_mssql': |
| 1629 | value = value.replace(microsecond=0) |
| 1630 | value = str(value) |
| 1631 | return Field.get_db_prep_save(self, value) |
| 1632 | |
| 1633 | def get_manipulator_field_objs(self): |
| 1634 | return [oldforms.TimeField] |
| 1635 | |
| 1636 | def flatten_data(self,follow, obj = None): |
| 1637 | val = self._get_val_from_obj(obj) |
| 1638 | return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')} |
| 1639 | |
| 1640 | def formfield(self): |
| 1641 | return forms.TimeField(required=not self.blank, label=capfirst(self.verbose_name)) |
| 1642 | |
| 1643 | class URLField(Field): |
| 1644 | def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): |
| 1645 | if verify_exists: |
| 1646 | kwargs.setdefault('validator_list', []).append(validators.isExistingURL) |
| 1647 | self.verify_exists = verify_exists |
| 1648 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1649 | |
| 1650 | def get_manipulator_field_objs(self): |
| 1651 | return [oldforms.URLField] |
| 1652 | |
| 1653 | def formfield(self): |
| 1654 | return forms.URLField(required=not self.blank, verify_exists=self.verify_exists, label=capfirst(self.verbose_name)) |
| 1655 | |
| 1656 | class USStateField(Field): |
| 1657 | def get_manipulator_field_objs(self): |
| 1658 | return [oldforms.USStateField] |
| 1659 | |
| 1660 | class XMLField(TextField): |
| 1661 | def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): |
| 1662 | self.schema_path = schema_path |
| 1663 | Field.__init__(self, verbose_name, name, **kwargs) |
| 1664 | |
| 1665 | def get_internal_type(self): |
| 1666 | return "TextField" |
| 1667 | |
| 1668 | def get_manipulator_field_objs(self): |
| 1669 | return [curry(oldforms.XMLLargeTextField, schema_path=self.schema_path)] |
| 1670 | |
| 1671 | class OrderingField(IntegerField): |
| 1672 | empty_strings_allowed=False |
| 1673 | def __init__(self, with_respect_to, **kwargs): |
| 1674 | self.wrt = with_respect_to |
| 1675 | kwargs['null'] = True |
| 1676 | IntegerField.__init__(self, **kwargs ) |
| 1677 | |
| 1678 | def get_internal_type(self): |
| 1679 | return "IntegerField" |
| 1680 | |
| 1681 | def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True): |
| 1682 | return [oldforms.HiddenField(name_prefix + self.name)] |