2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2012-05-23 02:26:46 +08:00
|
|
|
import collections
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2007-09-08 13:11:17 +08:00
|
|
|
import datetime
|
2009-12-18 06:06:41 +08:00
|
|
|
import decimal
|
2010-03-21 01:56:22 +08:00
|
|
|
import math
|
2011-11-20 07:27:20 +08:00
|
|
|
import warnings
|
2012-12-15 07:26:08 +08:00
|
|
|
from base64 import b64decode, b64encode
|
2010-05-04 22:00:30 +08:00
|
|
|
from itertools import tee
|
2009-12-18 06:06:41 +08:00
|
|
|
|
2008-08-11 20:11:25 +08:00
|
|
|
from django.db import connection
|
2013-01-19 20:09:46 +08:00
|
|
|
from django.db.models.loading import get_model
|
2008-04-28 15:07:17 +08:00
|
|
|
from django.db.models.query_utils import QueryWrapper
|
2005-08-02 05:29:52 +08:00
|
|
|
from django.conf import settings
|
2008-07-19 09:22:26 +08:00
|
|
|
from django import forms
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core import exceptions, validators
|
2008-06-26 11:11:32 +08:00
|
|
|
from django.utils.datastructures import DictWrapper
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils.dateparse import parse_date, parse_datetime, parse_time
|
2012-05-08 01:08:20 +08:00
|
|
|
from django.utils.functional import curry, total_ordering
|
2005-08-02 05:29:52 +08:00
|
|
|
from django.utils.text import capfirst
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.utils import timezone
|
2010-02-02 08:41:28 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2012-12-15 07:26:08 +08:00
|
|
|
from django.utils.encoding import smart_text, force_text, force_bytes
|
2011-07-13 17:35:51 +08:00
|
|
|
from django.utils.ipv6 import clean_ipv6_address
|
2012-07-20 20:22:00 +08:00
|
|
|
from django.utils import six
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
class Empty(object):
|
|
|
|
pass
|
|
|
|
|
2006-03-01 11:51:55 +08:00
|
|
|
class NOT_PROVIDED:
|
|
|
|
pass
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
# The values to use for "blank" in SelectFields. Will be appended to the start
|
|
|
|
# of most "choices" lists.
|
2005-08-02 05:29:52 +08:00
|
|
|
BLANK_CHOICE_DASH = [("", "---------")]
|
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def _load_field(app_label, model_name, field_name):
|
|
|
|
return get_model(app_label, model_name)._meta.get_field_by_name(field_name)[0]
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class FieldDoesNotExist(Exception):
|
|
|
|
pass
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2005-11-10 07:37:41 +08:00
|
|
|
# A guide to Field parameters:
|
|
|
|
#
|
2006-05-02 09:31:56 +08:00
|
|
|
# * name: The name of the field specifed in the model.
|
2005-11-10 07:37:41 +08:00
|
|
|
# * attname: The attribute to use on the model object. This is the same as
|
|
|
|
# "name", except in the case of ForeignKeys, where "_id" is
|
|
|
|
# appended.
|
|
|
|
# * db_column: The db_column specified in the model (or None).
|
|
|
|
# * column: The database column for this field. This is the same as
|
|
|
|
# "attname", except if db_column is specified.
|
|
|
|
#
|
|
|
|
# Code that introspects values, or does other dynamic things, should use
|
|
|
|
# attname. For example, this gets the primary key value of object "obj":
|
|
|
|
#
|
|
|
|
# getattr(obj, opts.pk.attname)
|
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def _empty(of_cls):
|
|
|
|
new = Empty()
|
|
|
|
new.__class__ = of_cls
|
|
|
|
return new
|
|
|
|
|
2012-05-08 01:08:20 +08:00
|
|
|
@total_ordering
|
2005-08-02 05:29:52 +08:00
|
|
|
class Field(object):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""Base class for all field types"""
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
# Designates whether empty strings fundamentally are allowed at the
|
|
|
|
# database level.
|
|
|
|
empty_strings_allowed = True
|
2013-03-06 15:28:12 +08:00
|
|
|
empty_values = list(validators.EMPTY_VALUES)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
# These track each time a Field instance is created. Used to retain order.
|
|
|
|
# The auto_creation_counter is used for fields that Django implicitly
|
|
|
|
# creates, creation_counter is used for all user-specified fields.
|
2005-08-26 06:51:30 +08:00
|
|
|
creation_counter = 0
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
auto_creation_counter = -1
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [] # Default set of validators
|
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('Value %r is not a valid choice.'),
|
|
|
|
'null': _('This field cannot be null.'),
|
|
|
|
'blank': _('This field cannot be blank.'),
|
|
|
|
'unique': _('%(model_name)s with this %(field_label)s '
|
|
|
|
'already exists.'),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2009-12-17 02:13:34 +08:00
|
|
|
# Generic field type description, usually overriden by subclasses
|
|
|
|
def _description(self):
|
2012-06-08 00:08:47 +08:00
|
|
|
return _('Field of type: %(field_type)s') % {
|
2009-12-17 02:13:34 +08:00
|
|
|
'field_type': self.__class__.__name__
|
|
|
|
}
|
|
|
|
description = property(_description)
|
|
|
|
|
2005-08-26 06:51:30 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, primary_key=False,
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
max_length=None, unique=False, blank=False, null=False,
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
|
|
|
|
serialize=True, unique_for_date=None, unique_for_month=None,
|
|
|
|
unique_for_year=None, choices=None, help_text='', db_column=None,
|
2010-01-05 11:56:19 +08:00
|
|
|
db_tablespace=None, auto_created=False, validators=[],
|
|
|
|
error_messages=None):
|
2005-08-02 05:29:52 +08:00
|
|
|
self.name = name
|
2006-05-02 09:31:56 +08:00
|
|
|
self.verbose_name = verbose_name
|
2005-08-02 05:29:52 +08:00
|
|
|
self.primary_key = primary_key
|
2008-06-30 12:46:59 +08:00
|
|
|
self.max_length, self._unique = max_length, unique
|
2005-08-02 05:29:52 +08:00
|
|
|
self.blank, self.null = blank, null
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
self.rel = rel
|
|
|
|
self.default = default
|
2005-08-02 05:29:52 +08:00
|
|
|
self.editable = editable
|
2007-03-19 19:57:53 +08:00
|
|
|
self.serialize = serialize
|
2011-10-13 16:11:00 +08:00
|
|
|
self.unique_for_date, self.unique_for_month = (unique_for_date,
|
|
|
|
unique_for_month)
|
2005-08-02 05:29:52 +08:00
|
|
|
self.unique_for_year = unique_for_year
|
2006-09-26 14:33:32 +08:00
|
|
|
self._choices = choices or []
|
2005-08-02 05:29:52 +08:00
|
|
|
self.help_text = help_text
|
2005-08-26 06:51:30 +08:00
|
|
|
self.db_column = db_column
|
2007-12-02 03:23:49 +08:00
|
|
|
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
|
2008-08-25 11:51:25 +08:00
|
|
|
self.auto_created = auto_created
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
# Set db_index to True if the field has a relationship and doesn't
|
|
|
|
# explicitly set db_index.
|
2006-05-02 09:31:56 +08:00
|
|
|
self.db_index = db_index
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
# Adjust the appropriate creation counter, and save our local copy.
|
|
|
|
if auto_created:
|
|
|
|
self.creation_counter = Field.auto_creation_counter
|
|
|
|
Field.auto_creation_counter -= 1
|
|
|
|
else:
|
|
|
|
self.creation_counter = Field.creation_counter
|
|
|
|
Field.creation_counter += 1
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
self.validators = self.default_validators + validators
|
|
|
|
|
|
|
|
messages = {}
|
|
|
|
for c in reversed(self.__class__.__mro__):
|
|
|
|
messages.update(getattr(c, 'default_error_messages', {}))
|
|
|
|
messages.update(error_messages or {})
|
|
|
|
self.error_messages = messages
|
|
|
|
|
2012-05-08 01:08:20 +08:00
|
|
|
def __eq__(self, other):
|
|
|
|
# Needed for @total_ordering
|
|
|
|
if isinstance(other, Field):
|
|
|
|
return self.creation_counter == other.creation_counter
|
|
|
|
return NotImplemented
|
|
|
|
|
|
|
|
def __lt__(self, other):
|
2006-05-02 09:31:56 +08:00
|
|
|
# This is needed because bisect does not take a comparison function.
|
2012-05-08 01:08:20 +08:00
|
|
|
if isinstance(other, Field):
|
|
|
|
return self.creation_counter < other.creation_counter
|
|
|
|
return NotImplemented
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-02-26 05:53:08 +08:00
|
|
|
def __hash__(self):
|
|
|
|
return hash(self.creation_counter)
|
2012-07-21 16:01:46 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def __deepcopy__(self, memodict):
|
|
|
|
# We don't have to deepcopy very much here, since most things are not
|
|
|
|
# intended to be altered after initial creation.
|
|
|
|
obj = copy.copy(self)
|
|
|
|
if self.rel:
|
|
|
|
obj.rel = copy.copy(self.rel)
|
|
|
|
memodict[id(self)] = obj
|
|
|
|
return obj
|
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def __copy__(self):
|
|
|
|
# We need to avoid hitting __reduce__, so define this
|
|
|
|
# slightly weird copy construct.
|
|
|
|
obj = Empty()
|
|
|
|
obj.__class__ = self.__class__
|
|
|
|
obj.__dict__ = self.__dict__.copy()
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def __reduce__(self):
|
|
|
|
"""
|
|
|
|
Pickling should return the model._meta.fields instance of the field,
|
|
|
|
not a new copy of that field. So, we use the app cache to load the
|
|
|
|
model and then the field back.
|
|
|
|
"""
|
|
|
|
if not hasattr(self, 'model'):
|
|
|
|
# Fields are sometimes used without attaching them to models (for
|
|
|
|
# example in aggregation). In this case give back a plain field
|
|
|
|
# instance. The code below will create a new empty instance of
|
|
|
|
# class self.__class__, then update its dict with self.__dict__
|
|
|
|
# values - so, this is very close to normal pickle.
|
|
|
|
return _empty, (self.__class__,), self.__dict__
|
|
|
|
if self.model._deferred:
|
|
|
|
# Deferred model will not be found from the app cache. This could
|
|
|
|
# be fixed by reconstructing the deferred model on unpickle.
|
|
|
|
raise RuntimeError("Fields of deferred models can't be reduced")
|
|
|
|
return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
|
|
|
|
self.name)
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
"""
|
|
|
|
Converts the input value into the expected Python data type, raising
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
django.core.exceptions.ValidationError if the data can't be converted.
|
|
|
|
Returns the converted value. Subclasses should override this.
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
return value
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def run_validators(self, value):
|
2013-03-06 15:28:12 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
return
|
|
|
|
|
|
|
|
errors = []
|
|
|
|
for v in self.validators:
|
|
|
|
try:
|
|
|
|
v(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except exceptions.ValidationError as e:
|
2010-01-05 11:56:19 +08:00
|
|
|
if hasattr(e, 'code') and e.code in self.error_messages:
|
|
|
|
message = self.error_messages[e.code]
|
|
|
|
if e.params:
|
|
|
|
message = message % e.params
|
|
|
|
errors.append(message)
|
|
|
|
else:
|
|
|
|
errors.extend(e.messages)
|
|
|
|
if errors:
|
|
|
|
raise exceptions.ValidationError(errors)
|
|
|
|
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
"""
|
|
|
|
Validates value and throws ValidationError. Subclasses should override
|
|
|
|
this to provide validation logic.
|
|
|
|
"""
|
|
|
|
if not self.editable:
|
|
|
|
# Skip validation for non-editable fields.
|
|
|
|
return
|
2012-08-06 16:42:21 +08:00
|
|
|
|
2013-03-06 15:28:12 +08:00
|
|
|
if self._choices and value not in self.empty_values:
|
2010-02-02 08:41:28 +08:00
|
|
|
for option_key, option_value in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(option_value, (list, tuple)):
|
2011-10-13 16:11:00 +08:00
|
|
|
# This is an optgroup, so look inside the group for
|
|
|
|
# options.
|
2010-02-02 08:41:28 +08:00
|
|
|
for optgroup_key, optgroup_value in option_value:
|
|
|
|
if value == optgroup_key:
|
|
|
|
return
|
|
|
|
elif value == option_key:
|
|
|
|
return
|
2011-11-18 21:01:06 +08:00
|
|
|
msg = self.error_messages['invalid_choice'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
if value is None and not self.null:
|
|
|
|
raise exceptions.ValidationError(self.error_messages['null'])
|
|
|
|
|
2013-03-06 15:28:12 +08:00
|
|
|
if not self.blank and value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
raise exceptions.ValidationError(self.error_messages['blank'])
|
|
|
|
|
|
|
|
def clean(self, value, model_instance):
|
|
|
|
"""
|
2011-10-13 16:11:00 +08:00
|
|
|
Convert the value's type and run validation. Validation errors
|
|
|
|
from to_python and validate are propagated. The correct value is
|
|
|
|
returned if no error is raised.
|
2010-01-05 11:56:19 +08:00
|
|
|
"""
|
|
|
|
value = self.to_python(value)
|
|
|
|
self.validate(value, model_instance)
|
|
|
|
self.run_validators(value)
|
|
|
|
return value
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
2007-07-20 14:28:56 +08:00
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
Returns the database column data type for this field, for the provided
|
|
|
|
connection.
|
2007-07-20 14:28:56 +08:00
|
|
|
"""
|
|
|
|
# The default implementation of this method looks at the
|
|
|
|
# backend-specific DATA_TYPES dictionary, looking up the field by its
|
|
|
|
# "internal type".
|
|
|
|
#
|
|
|
|
# A Field class can implement the get_internal_type() method to specify
|
|
|
|
# which *preexisting* Django Field class it's most similar to -- i.e.,
|
2011-10-13 16:11:00 +08:00
|
|
|
# a custom field might be represented by a TEXT column type, which is
|
|
|
|
# the same as the TextField Django field type, which means the custom
|
|
|
|
# field's get_internal_type() returns 'TextField'.
|
2007-07-20 14:28:56 +08:00
|
|
|
#
|
2008-08-11 20:11:25 +08:00
|
|
|
# But the limitation of the get_internal_type() / data_types approach
|
2007-07-20 14:28:56 +08:00
|
|
|
# is that it cannot handle database column types that aren't already
|
|
|
|
# mapped to one of the built-in Django field types. In this case, you
|
|
|
|
# can implement db_type() instead of get_internal_type() to specify
|
|
|
|
# exactly which wacky database column type you want to use.
|
2008-06-26 11:11:32 +08:00
|
|
|
data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
try:
|
2011-10-13 16:11:00 +08:00
|
|
|
return (connection.creation.data_types[self.get_internal_type()]
|
|
|
|
% data)
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
except KeyError:
|
2007-11-05 21:59:42 +08:00
|
|
|
return None
|
2007-07-20 14:28:56 +08:00
|
|
|
|
2011-08-13 19:53:42 +08:00
|
|
|
@property
|
2008-06-30 12:46:59 +08:00
|
|
|
def unique(self):
|
|
|
|
return self._unique or self.primary_key
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def set_attributes_from_name(self, name):
|
2011-08-13 19:53:42 +08:00
|
|
|
if not self.name:
|
|
|
|
self.name = name
|
2005-11-10 07:37:41 +08:00
|
|
|
self.attname, self.column = self.get_attname_column()
|
2011-08-13 19:53:42 +08:00
|
|
|
if self.verbose_name is None and self.name:
|
|
|
|
self.verbose_name = self.name.replace('_', ' ')
|
2006-05-02 09:31:56 +08:00
|
|
|
|
|
|
|
def contribute_to_class(self, cls, name):
|
|
|
|
self.set_attributes_from_name(name)
|
2010-04-15 20:41:08 +08:00
|
|
|
self.model = cls
|
2006-05-02 09:31:56 +08:00
|
|
|
cls._meta.add_field(self)
|
|
|
|
if self.choices:
|
2011-10-13 16:11:00 +08:00
|
|
|
setattr(cls, 'get_%s_display' % self.name,
|
|
|
|
curry(cls._get_FIELD_display, field=self))
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def get_attname(self):
|
|
|
|
return self.name
|
|
|
|
|
2005-11-10 07:37:41 +08:00
|
|
|
def get_attname_column(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
attname = self.get_attname()
|
2005-11-10 07:37:41 +08:00
|
|
|
column = self.db_column or attname
|
|
|
|
return attname, column
|
2005-08-26 06:51:30 +08:00
|
|
|
|
|
|
|
def get_cache_name(self):
|
|
|
|
return '_%s_cache' % self.name
|
|
|
|
|
2005-09-29 07:08:47 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return self.__class__.__name__
|
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns field's value just before saving.
|
|
|
|
"""
|
2006-05-30 01:08:58 +08:00
|
|
|
return getattr(model_instance, self.attname)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Perform preliminary non-db specific value checks and conversions.
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2008-07-29 13:09:29 +08:00
|
|
|
"""Returns field's value prepared for interacting with the database
|
|
|
|
backend.
|
|
|
|
|
|
|
|
Used by the default implementations of ``get_db_prep_save``and
|
|
|
|
`get_db_prep_lookup```
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
return value
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns field's value prepared for saving into a database.
|
|
|
|
"""
|
|
|
|
return self.get_db_prep_value(value, connection=connection,
|
|
|
|
prepared=False)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Perform preliminary non-db specific lookup checks and conversions
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if hasattr(value, 'prepare'):
|
|
|
|
return value.prepare()
|
|
|
|
if hasattr(value, '_prepare'):
|
|
|
|
return value._prepare()
|
|
|
|
|
|
|
|
if lookup_type in (
|
2013-02-10 23:15:49 +08:00
|
|
|
'iexact', 'contains', 'icontains',
|
|
|
|
'startswith', 'istartswith', 'endswith', 'iendswith',
|
|
|
|
'month', 'day', 'week_day', 'hour', 'minute', 'second',
|
|
|
|
'isnull', 'search', 'regex', 'iregex',
|
2009-12-22 23:18:51 +08:00
|
|
|
):
|
|
|
|
return value
|
|
|
|
elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
|
|
|
|
return self.get_prep_value(value)
|
|
|
|
elif lookup_type in ('range', 'in'):
|
|
|
|
return [self.get_prep_value(v) for v in value]
|
|
|
|
elif lookup_type == 'year':
|
|
|
|
try:
|
|
|
|
return int(value)
|
|
|
|
except ValueError:
|
2011-10-13 16:11:00 +08:00
|
|
|
raise ValueError("The __year lookup type requires an integer "
|
|
|
|
"argument")
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
raise TypeError("Field has invalid lookup: %s" % lookup_type)
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def get_db_prep_lookup(self, lookup_type, value, connection,
|
|
|
|
prepared=False):
|
|
|
|
"""
|
|
|
|
Returns field's value prepared for database lookup.
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_lookup(lookup_type, value)
|
|
|
|
if hasattr(value, 'get_compiler'):
|
|
|
|
value = value.get_compiler(connection=connection)
|
2009-03-01 12:12:30 +08:00
|
|
|
if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'):
|
2013-03-02 07:06:56 +08:00
|
|
|
# If the value has a relabeled_clone method it means the
|
|
|
|
# value will be handled later on.
|
|
|
|
if hasattr(value, 'relabeled_clone'):
|
2009-01-29 18:46:36 +08:00
|
|
|
return value
|
2009-03-04 12:56:20 +08:00
|
|
|
if hasattr(value, 'as_sql'):
|
2009-03-01 12:12:30 +08:00
|
|
|
sql, params = value.as_sql()
|
2009-03-04 12:56:20 +08:00
|
|
|
else:
|
2009-12-22 23:18:51 +08:00
|
|
|
sql, params = value._as_sql(connection=connection)
|
2008-04-28 15:07:17 +08:00
|
|
|
return QueryWrapper(('(%s)' % sql), params)
|
2009-01-29 18:46:36 +08:00
|
|
|
|
2013-02-10 23:15:49 +08:00
|
|
|
if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute',
|
|
|
|
'second', 'search', 'regex', 'iregex'):
|
2005-08-02 05:29:52 +08:00
|
|
|
return [value]
|
2008-07-29 13:09:29 +08:00
|
|
|
elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
|
2011-10-13 16:11:00 +08:00
|
|
|
return [self.get_db_prep_value(value, connection=connection,
|
|
|
|
prepared=prepared)]
|
2005-08-02 05:29:52 +08:00
|
|
|
elif lookup_type in ('range', 'in'):
|
2011-10-13 16:11:00 +08:00
|
|
|
return [self.get_db_prep_value(v, connection=connection,
|
|
|
|
prepared=prepared) for v in value]
|
2005-12-05 02:54:44 +08:00
|
|
|
elif lookup_type in ('contains', 'icontains'):
|
2008-06-16 11:15:04 +08:00
|
|
|
return ["%%%s%%" % connection.ops.prep_for_like_query(value)]
|
2005-08-02 05:29:52 +08:00
|
|
|
elif lookup_type == 'iexact':
|
2008-08-28 13:42:05 +08:00
|
|
|
return [connection.ops.prep_for_iexact_query(value)]
|
2005-12-05 02:54:44 +08:00
|
|
|
elif lookup_type in ('startswith', 'istartswith'):
|
2008-06-16 11:15:04 +08:00
|
|
|
return ["%s%%" % connection.ops.prep_for_like_query(value)]
|
2005-12-05 02:54:44 +08:00
|
|
|
elif lookup_type in ('endswith', 'iendswith'):
|
2008-06-16 11:15:04 +08:00
|
|
|
return ["%%%s" % connection.ops.prep_for_like_query(value)]
|
2005-08-02 05:29:52 +08:00
|
|
|
elif lookup_type == 'isnull':
|
|
|
|
return []
|
2007-02-14 14:32:32 +08:00
|
|
|
elif lookup_type == 'year':
|
2013-02-10 23:15:49 +08:00
|
|
|
if isinstance(self, DateTimeField):
|
|
|
|
return connection.ops.year_lookup_bounds_for_datetime_field(value)
|
|
|
|
elif isinstance(self, DateField):
|
2008-07-29 13:09:29 +08:00
|
|
|
return connection.ops.year_lookup_bounds_for_date_field(value)
|
2008-02-23 16:36:41 +08:00
|
|
|
else:
|
2013-02-10 23:15:49 +08:00
|
|
|
return [value] # this isn't supposed to happen
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def has_default(self):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns a boolean of whether this field has a default value.
|
|
|
|
"""
|
2006-03-01 11:51:55 +08:00
|
|
|
return self.default is not NOT_PROVIDED
|
2005-08-02 05:29:52 +08:00
|
|
|
|
|
|
|
def get_default(self):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns the default value for this field.
|
|
|
|
"""
|
2008-09-02 05:28:32 +08:00
|
|
|
if self.has_default():
|
2006-05-02 09:31:56 +08:00
|
|
|
if callable(self.default):
|
|
|
|
return self.default()
|
2012-07-21 16:00:10 +08:00
|
|
|
return force_text(self.default, strings_only=True)
|
2011-10-13 16:11:00 +08:00
|
|
|
if (not self.empty_strings_allowed or (self.null and
|
|
|
|
not connection.features.interprets_empty_strings_as_nulls)):
|
2005-08-02 05:29:52 +08:00
|
|
|
return None
|
|
|
|
return ""
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def get_validator_unique_lookup_type(self):
|
|
|
|
return '%s__exact' % self.name
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
|
2008-07-27 15:22:39 +08:00
|
|
|
"""Returns choices with a default blank choices included, for use
|
|
|
|
as SelectField choices for this field."""
|
2005-08-02 05:29:52 +08:00
|
|
|
first_choice = include_blank and blank_choice or []
|
|
|
|
if self.choices:
|
|
|
|
return first_choice + list(self.choices)
|
2006-05-02 09:31:56 +08:00
|
|
|
rel_model = self.rel.to
|
2006-08-01 22:20:01 +08:00
|
|
|
if hasattr(self.rel, 'get_related_field'):
|
2011-10-13 16:11:00 +08:00
|
|
|
lst = [(getattr(x, self.rel.get_related_field().attname),
|
2012-07-21 16:00:10 +08:00
|
|
|
smart_text(x))
|
2011-10-13 16:11:00 +08:00
|
|
|
for x in rel_model._default_manager.complex_filter(
|
|
|
|
self.rel.limit_choices_to)]
|
2006-08-01 22:20:01 +08:00
|
|
|
else:
|
2012-07-21 16:00:10 +08:00
|
|
|
lst = [(x._get_pk_val(), smart_text(x))
|
2011-10-13 16:11:00 +08:00
|
|
|
for x in rel_model._default_manager.complex_filter(
|
|
|
|
self.rel.limit_choices_to)]
|
2006-08-01 22:20:01 +08:00
|
|
|
return first_choice + lst
|
2005-11-26 05:20:09 +08:00
|
|
|
|
|
|
|
def get_choices_default(self):
|
2008-07-19 07:54:34 +08:00
|
|
|
return self.get_choices()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def get_flatchoices(self, include_blank=True,
|
|
|
|
blank_choice=BLANK_CHOICE_DASH):
|
|
|
|
"""
|
|
|
|
Returns flattened choices with a default blank choice included.
|
|
|
|
"""
|
2008-07-27 15:22:39 +08:00
|
|
|
first_choice = include_blank and blank_choice or []
|
2008-07-30 05:43:07 +08:00
|
|
|
return first_choice + list(self.flatchoices)
|
2008-07-27 15:22:39 +08:00
|
|
|
|
2005-11-26 05:20:09 +08:00
|
|
|
def _get_val_from_obj(self, obj):
|
2010-02-24 23:54:03 +08:00
|
|
|
if obj is not None:
|
2006-05-02 09:31:56 +08:00
|
|
|
return getattr(obj, self.attname)
|
2005-11-26 05:20:09 +08:00
|
|
|
else:
|
2006-05-02 09:31:56 +08:00
|
|
|
return self.get_default()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2005-11-26 05:20:09 +08:00
|
|
|
"""
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
Returns a string value of this field from the passed obj.
|
|
|
|
This is used by the serialization framework.
|
2005-11-26 05:20:09 +08:00
|
|
|
"""
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(self._get_val_from_obj(obj))
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def bind(self, fieldmapping, original, bound_field_class):
|
2005-11-26 05:20:09 +08:00
|
|
|
return bound_field_class(self, fieldmapping, original)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2006-09-26 14:33:32 +08:00
|
|
|
def _get_choices(self):
|
2012-05-23 02:26:46 +08:00
|
|
|
if isinstance(self._choices, collections.Iterator):
|
2006-09-26 14:33:32 +08:00
|
|
|
choices, self._choices = tee(self._choices)
|
|
|
|
return choices
|
|
|
|
else:
|
|
|
|
return self._choices
|
|
|
|
choices = property(_get_choices)
|
|
|
|
|
2008-07-19 15:53:02 +08:00
|
|
|
def _get_flatchoices(self):
|
2008-07-27 15:22:39 +08:00
|
|
|
"""Flattened version of choices tuple."""
|
2008-07-19 15:53:02 +08:00
|
|
|
flat = []
|
2008-07-27 15:22:39 +08:00
|
|
|
for choice, value in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(value, (list, tuple)):
|
2008-07-19 15:53:02 +08:00
|
|
|
flat.extend(value)
|
|
|
|
else:
|
|
|
|
flat.append((choice,value))
|
|
|
|
return flat
|
|
|
|
flatchoices = property(_get_flatchoices)
|
2008-07-27 15:22:39 +08:00
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
def save_form_data(self, instance, data):
|
|
|
|
setattr(instance, self.name, data)
|
2007-09-08 13:11:17 +08:00
|
|
|
|
2013-02-24 02:01:38 +08:00
|
|
|
def formfield(self, form_class=None, **kwargs):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns a django.forms.Field instance for this database Field.
|
|
|
|
"""
|
|
|
|
defaults = {'required': not self.blank,
|
|
|
|
'label': capfirst(self.verbose_name),
|
|
|
|
'help_text': self.help_text}
|
2008-09-02 03:20:03 +08:00
|
|
|
if self.has_default():
|
2008-09-02 05:28:32 +08:00
|
|
|
if callable(self.default):
|
2010-03-08 23:03:30 +08:00
|
|
|
defaults['initial'] = self.default
|
2008-09-02 05:28:32 +08:00
|
|
|
defaults['show_hidden_initial'] = True
|
2010-03-08 23:03:30 +08:00
|
|
|
else:
|
|
|
|
defaults['initial'] = self.get_default()
|
2007-04-28 22:18:03 +08:00
|
|
|
if self.choices:
|
2009-01-29 18:46:36 +08:00
|
|
|
# Fields with choices get special treatment.
|
2011-10-13 16:11:00 +08:00
|
|
|
include_blank = (self.blank or
|
|
|
|
not (self.has_default() or 'initial' in kwargs))
|
2008-09-01 04:11:11 +08:00
|
|
|
defaults['choices'] = self.get_choices(include_blank=include_blank)
|
|
|
|
defaults['coerce'] = self.to_python
|
|
|
|
if self.null:
|
|
|
|
defaults['empty_value'] = None
|
2013-02-24 02:01:38 +08:00
|
|
|
if form_class is None or not issubclass(form_class, forms.TypedChoiceField):
|
|
|
|
form_class = forms.TypedChoiceField
|
2008-09-02 03:20:03 +08:00
|
|
|
# Many of the subclass-specific formfield arguments (min_value,
|
|
|
|
# max_value) don't apply for choice fields, so be sure to only pass
|
|
|
|
# the values that TypedChoiceField will understand.
|
2012-08-08 22:33:15 +08:00
|
|
|
for k in list(kwargs):
|
2008-09-02 03:20:03 +08:00
|
|
|
if k not in ('coerce', 'empty_value', 'choices', 'required',
|
|
|
|
'widget', 'label', 'initial', 'help_text',
|
2010-03-07 09:50:58 +08:00
|
|
|
'error_messages', 'show_hidden_initial'):
|
2008-09-02 03:20:03 +08:00
|
|
|
del kwargs[k]
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2013-02-24 02:01:38 +08:00
|
|
|
if form_class is None:
|
|
|
|
form_class = forms.CharField
|
2007-04-28 21:55:24 +08:00
|
|
|
return form_class(**defaults)
|
2006-12-15 13:46:11 +08:00
|
|
|
|
2006-12-28 10:27:14 +08:00
|
|
|
def value_from_object(self, obj):
|
2011-10-13 16:11:00 +08:00
|
|
|
"""
|
|
|
|
Returns the value of this field in the given model instance.
|
|
|
|
"""
|
2006-12-28 10:27:14 +08:00
|
|
|
return getattr(obj, self.attname)
|
|
|
|
|
2011-05-03 19:51:37 +08:00
|
|
|
def __repr__(self):
|
|
|
|
"""
|
|
|
|
Displays the module, class and name of the field.
|
|
|
|
"""
|
|
|
|
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
|
|
|
|
name = getattr(self, 'name', None)
|
|
|
|
if name is not None:
|
|
|
|
return '<%s: %s>' % (path, name)
|
|
|
|
return '<%s>' % path
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class AutoField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("Integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value must be an integer."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2012-02-10 02:57:54 +08:00
|
|
|
|
2005-08-10 13:08:27 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2011-10-13 19:53:59 +08:00
|
|
|
assert kwargs.get('primary_key', False) is True, \
|
|
|
|
"%ss must have primary_key=True." % self.__class__.__name__
|
2006-05-02 09:31:56 +08:00
|
|
|
kwargs['blank'] = True
|
2005-08-10 13:08:27 +08:00
|
|
|
Field.__init__(self, *args, **kwargs)
|
|
|
|
|
2010-08-07 15:38:27 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "AutoField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return int(value)
|
|
|
|
except (TypeError, ValueError):
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
pass
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2012-04-25 02:03:14 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
value = connection.ops.validate_autopk_value(value)
|
|
|
|
return value
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return int(value)
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def contribute_to_class(self, cls, name):
|
2011-10-13 19:53:59 +08:00
|
|
|
assert not cls._meta.has_auto_field, \
|
|
|
|
"A model can't have more than one AutoField."
|
2006-05-02 09:31:56 +08:00
|
|
|
super(AutoField, self).contribute_to_class(cls, name)
|
|
|
|
cls._meta.has_auto_field = True
|
2007-09-15 02:12:36 +08:00
|
|
|
cls._meta.auto_field = self
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2006-12-16 05:22:13 +08:00
|
|
|
return None
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class BooleanField(Field):
|
2009-04-11 08:06:53 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value must be either True or False."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Boolean (Either True or False)")
|
2012-02-10 02:57:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['blank'] = True
|
2008-07-22 12:49:32 +08:00
|
|
|
if 'default' not in kwargs and not kwargs.get('null'):
|
|
|
|
kwargs['default'] = False
|
2005-08-02 05:29:52 +08:00
|
|
|
Field.__init__(self, *args, **kwargs)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "BooleanField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2010-02-25 01:36:18 +08:00
|
|
|
if value in (True, False):
|
|
|
|
# if value is 1 or 0 than it's equal to True or False, but we want
|
|
|
|
# to return a true bool for semantic reasons.
|
|
|
|
return bool(value)
|
|
|
|
if value in ('t', 'True', '1'):
|
|
|
|
return True
|
|
|
|
if value in ('f', 'False', '0'):
|
|
|
|
return False
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2010-10-09 16:12:50 +08:00
|
|
|
# Special-case handling for filters coming from a Web request (e.g. the
|
2008-08-29 10:40:56 +08:00
|
|
|
# admin interface). Only works for scalar values (not lists). If you're
|
|
|
|
# passing in a list, you might as well make things the right type when
|
|
|
|
# constructing the list.
|
|
|
|
if value in ('1', '0'):
|
|
|
|
value = bool(int(value))
|
2009-12-22 23:18:51 +08:00
|
|
|
return super(BooleanField, self).get_prep_lookup(lookup_type, value)
|
2008-08-29 10:40:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return bool(value)
|
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2009-04-11 03:54:31 +08:00
|
|
|
# Unlike most fields, BooleanField figures out include_blank from
|
|
|
|
# self.null instead of self.blank.
|
|
|
|
if self.choices:
|
2011-10-13 16:11:00 +08:00
|
|
|
include_blank = (self.null or
|
|
|
|
not (self.has_default() or 'initial' in kwargs))
|
|
|
|
defaults = {'choices': self.get_choices(
|
|
|
|
include_blank=include_blank)}
|
2009-04-11 03:54:31 +08:00
|
|
|
else:
|
|
|
|
defaults = {'form_class': forms.BooleanField}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(BooleanField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class CharField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("String (up to %(max_length)s)")
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(CharField, self).__init__(*args, **kwargs)
|
|
|
|
self.validators.append(validators.MaxLengthValidator(self.max_length))
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "CharField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types) or value is None:
|
2006-05-02 09:31:56 +08:00
|
|
|
return value
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2010-01-10 06:05:10 +08:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
return self.to_python(value)
|
2010-03-21 04:01:06 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2010-01-05 11:56:19 +08:00
|
|
|
# Passing max_length to forms.CharField means that the value's length
|
|
|
|
# will be validated twice. This is considered acceptable since we want
|
|
|
|
# the value in the form field (to pass into widget for example).
|
2007-08-05 13:14:46 +08:00
|
|
|
defaults = {'max_length': self.max_length}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(CharField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
# TODO: Maybe move this into contrib, because it's specialized.
|
2005-08-02 05:29:52 +08:00
|
|
|
class CommaSeparatedIntegerField(CharField):
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_comma_separated_integer_list]
|
|
|
|
description = _("Comma-separated integers")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-29 04:58:10 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {
|
|
|
|
'error_messages': {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter only digits separated by commas.'),
|
2008-08-29 04:58:10 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(CommaSeparatedIntegerField, self).formfield(**defaults)
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class DateField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value has an invalid date format. It must be "
|
|
|
|
"in YYYY-MM-DD format."),
|
|
|
|
'invalid_date': _("'%s' value has the correct format (YYYY-MM-DD) "
|
|
|
|
"but it is an invalid date."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2011-11-18 21:01:06 +08:00
|
|
|
description = _("Date (without time)")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, auto_now=False,
|
|
|
|
auto_now_add=False, **kwargs):
|
2005-08-02 05:29:52 +08:00
|
|
|
self.auto_now, self.auto_now_add = auto_now, auto_now_add
|
|
|
|
if auto_now or auto_now_add:
|
|
|
|
kwargs['editable'] = False
|
2005-11-26 05:20:09 +08:00
|
|
|
kwargs['blank'] = True
|
2005-08-26 06:51:30 +08:00
|
|
|
Field.__init__(self, verbose_name, name, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DateField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2007-02-26 13:07:12 +08:00
|
|
|
if value is None:
|
|
|
|
return value
|
2006-05-02 09:31:56 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
2012-05-01 16:40:25 +08:00
|
|
|
if settings.USE_TZ and timezone.is_aware(value):
|
2012-06-01 14:09:58 +08:00
|
|
|
# Convert aware datetimes to the default time zone
|
2012-05-01 16:40:25 +08:00
|
|
|
# before casting them to dates (#17742).
|
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_naive(value, default_timezone)
|
2006-05-02 09:31:56 +08:00
|
|
|
return value.date()
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return value
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2006-07-01 02:57:23 +08:00
|
|
|
try:
|
2011-11-18 21:01:06 +08:00
|
|
|
parsed = parse_date(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
|
|
|
except ValueError:
|
|
|
|
msg = self.error_messages['invalid_date'] % value
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2005-08-10 11:50:46 +08:00
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2010-10-09 00:14:10 +08:00
|
|
|
value = datetime.date.today()
|
2006-05-30 01:08:58 +08:00
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return super(DateField, self).pre_save(model_instance, add)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def contribute_to_class(self, cls, name):
|
|
|
|
super(DateField,self).contribute_to_class(cls, name)
|
|
|
|
if not self.null:
|
|
|
|
setattr(cls, 'get_next_by_%s' % self.name,
|
2011-10-13 16:11:00 +08:00
|
|
|
curry(cls._get_next_or_previous_by_FIELD, field=self,
|
|
|
|
is_next=True))
|
2006-05-02 09:31:56 +08:00
|
|
|
setattr(cls, 'get_previous_by_%s' % self.name,
|
2011-10-13 16:11:00 +08:00
|
|
|
curry(cls._get_next_or_previous_by_FIELD, field=self,
|
|
|
|
is_next=False))
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2013-02-10 23:15:49 +08:00
|
|
|
# For dates lookups, convert the value to an int
|
|
|
|
# so the database backend always sees a consistent type.
|
|
|
|
if lookup_type in ('month', 'day', 'week_day', 'hour', 'minute', 'second'):
|
2009-12-22 23:18:51 +08:00
|
|
|
return int(value)
|
|
|
|
return super(DateField, self).get_prep_lookup(lookup_type, value)
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
return self.to_python(value)
|
2008-08-25 11:17:06 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2008-07-29 13:09:29 +08:00
|
|
|
# Casts dates into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
return connection.ops.value_to_db_date(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2005-11-26 05:20:09 +08:00
|
|
|
val = self._get_val_from_obj(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return '' if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2007-04-28 21:55:24 +08:00
|
|
|
defaults = {'form_class': forms.DateField}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(DateField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class DateTimeField(DateField):
|
2011-11-18 21:01:06 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value has an invalid format. It must be in "
|
|
|
|
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
|
|
|
|
'invalid_date': _("'%s' value has the correct format "
|
|
|
|
"(YYYY-MM-DD) but it is an invalid date."),
|
|
|
|
'invalid_datetime': _("'%s' value has the correct format "
|
|
|
|
"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
|
|
|
|
"but it is an invalid date/time."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Date (with time)")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# __init__ is inherited from DateField
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DateTimeField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2007-02-26 13:07:12 +08:00
|
|
|
if value is None:
|
|
|
|
return value
|
2006-05-02 09:31:56 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value
|
|
|
|
if isinstance(value, datetime.date):
|
2012-01-24 18:00:39 +08:00
|
|
|
value = datetime.datetime(value.year, value.month, value.day)
|
|
|
|
if settings.USE_TZ:
|
2012-01-24 18:32:28 +08:00
|
|
|
# For backwards compatibility, interpret naive datetimes in
|
|
|
|
# local time. This won't work during DST change, but we can't
|
|
|
|
# do much about it, so we let the exceptions percolate up the
|
|
|
|
# call stack.
|
2012-06-08 00:08:47 +08:00
|
|
|
warnings.warn("DateTimeField received a naive datetime (%s)"
|
|
|
|
" while time zone support is active." % value,
|
2012-01-24 18:32:28 +08:00
|
|
|
RuntimeWarning)
|
2012-01-24 18:00:39 +08:00
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_aware(value, default_timezone)
|
|
|
|
return value
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
try:
|
|
|
|
parsed = parse_datetime(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
|
|
|
except ValueError:
|
|
|
|
msg = self.error_messages['invalid_datetime'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
|
|
|
|
|
|
|
try:
|
|
|
|
parsed = parse_date(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return datetime.datetime(parsed.year, parsed.month, parsed.day)
|
2006-05-02 09:31:56 +08:00
|
|
|
except ValueError:
|
2011-11-18 21:01:06 +08:00
|
|
|
msg = self.error_messages['invalid_date'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
|
|
|
|
|
|
|
msg = self.error_messages['invalid'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2010-10-09 00:14:10 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2011-11-18 21:01:06 +08:00
|
|
|
value = timezone.now()
|
2010-10-09 00:14:10 +08:00
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return super(DateTimeField, self).pre_save(model_instance, add)
|
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# contribute_to_class is inherited from DateField, it registers
|
|
|
|
# get_next_by_FOO and get_prev_by_FOO
|
|
|
|
|
|
|
|
# get_prep_lookup is inherited from DateField
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2011-11-18 21:01:06 +08:00
|
|
|
value = self.to_python(value)
|
2011-11-25 17:25:43 +08:00
|
|
|
if value is not None and settings.USE_TZ and timezone.is_naive(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
# For backwards compatibility, interpret naive datetimes in local
|
|
|
|
# time. This won't work during DST change, but we can't do much
|
|
|
|
# about it, so we let the exceptions percolate up the call stack.
|
2012-06-08 00:08:47 +08:00
|
|
|
warnings.warn("DateTimeField received a naive datetime (%s)"
|
|
|
|
" while time zone support is active." % value,
|
2011-11-20 07:27:20 +08:00
|
|
|
RuntimeWarning)
|
2011-11-18 21:01:06 +08:00
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_aware(value, default_timezone)
|
|
|
|
return value
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2011-11-18 21:01:06 +08:00
|
|
|
# Casts datetimes into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
return connection.ops.value_to_db_datetime(value)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2005-11-26 05:20:09 +08:00
|
|
|
val = self._get_val_from_obj(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return '' if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2007-04-28 21:55:24 +08:00
|
|
|
defaults = {'form_class': forms.DateTimeField}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(DateTimeField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
class DecimalField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value must be a decimal number."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Decimal number")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, max_digits=None,
|
|
|
|
decimal_places=None, **kwargs):
|
2007-05-21 09:29:58 +08:00
|
|
|
self.max_digits, self.decimal_places = max_digits, decimal_places
|
|
|
|
Field.__init__(self, verbose_name, name, **kwargs)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DecimalField"
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return decimal.Decimal(value)
|
|
|
|
except decimal.InvalidOperation:
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
|
|
|
def _format(self, value):
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types) or value is None:
|
2007-05-21 09:29:58 +08:00
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return self.format_number(value)
|
|
|
|
|
|
|
|
def format_number(self, value):
|
|
|
|
"""
|
|
|
|
Formats a number into a string with the requisite number of digits and
|
|
|
|
decimal places.
|
|
|
|
"""
|
2008-07-29 13:09:29 +08:00
|
|
|
# Method moved to django.db.backends.util.
|
|
|
|
#
|
|
|
|
# It is preserved because it is used by the oracle backend
|
|
|
|
# (django.db.backends.oracle.query), and also for
|
|
|
|
# backwards-compatibility with any external code which may have used
|
|
|
|
# this method.
|
|
|
|
from django.db.backends import util
|
|
|
|
return util.format_number(value, self.max_digits, self.decimal_places)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2008-07-30 08:18:49 +08:00
|
|
|
return connection.ops.value_to_db_decimal(self.to_python(value),
|
|
|
|
self.max_digits, self.decimal_places)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2009-04-12 13:32:23 +08:00
|
|
|
return self.to_python(value)
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {
|
|
|
|
'max_digits': self.max_digits,
|
|
|
|
'decimal_places': self.decimal_places,
|
|
|
|
'form_class': forms.DecimalField,
|
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(DecimalField, self).formfield(**defaults)
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class EmailField(CharField):
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_email]
|
2012-09-26 20:14:51 +08:00
|
|
|
description = _("Email address")
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2005-11-21 06:41:41 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2012-03-31 21:55:03 +08:00
|
|
|
# max_length should be overridden to 254 characters to be fully
|
2012-03-30 02:39:21 +08:00
|
|
|
# compliant with RFCs 3696 and 5321
|
|
|
|
|
2007-09-20 07:33:57 +08:00
|
|
|
kwargs['max_length'] = kwargs.get('max_length', 75)
|
2006-05-02 09:31:56 +08:00
|
|
|
CharField.__init__(self, *args, **kwargs)
|
2005-11-21 06:41:41 +08:00
|
|
|
|
2010-08-05 11:59:20 +08:00
|
|
|
def formfield(self, **kwargs):
|
2011-10-13 16:11:00 +08:00
|
|
|
# As with CharField, this will cause email validation to be performed
|
|
|
|
# twice.
|
2010-08-05 11:59:20 +08:00
|
|
|
defaults = {
|
|
|
|
'form_class': forms.EmailField,
|
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(EmailField, self).formfield(**defaults)
|
|
|
|
|
2005-10-12 12:14:21 +08:00
|
|
|
class FilePathField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("File path")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, path='', match=None,
|
2012-04-22 22:44:08 +08:00
|
|
|
recursive=False, allow_files=True, allow_folders=False, **kwargs):
|
2005-10-12 12:14:21 +08:00
|
|
|
self.path, self.match, self.recursive = path, match, recursive
|
2012-04-22 22:44:08 +08:00
|
|
|
self.allow_files, self.allow_folders = allow_files, allow_folders
|
2007-09-20 07:33:57 +08:00
|
|
|
kwargs['max_length'] = kwargs.get('max_length', 100)
|
2005-10-12 12:14:21 +08:00
|
|
|
Field.__init__(self, verbose_name, name, **kwargs)
|
2008-06-16 11:15:04 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {
|
|
|
|
'path': self.path,
|
|
|
|
'match': self.match,
|
|
|
|
'recursive': self.recursive,
|
|
|
|
'form_class': forms.FilePathField,
|
2012-04-22 22:44:08 +08:00
|
|
|
'allow_files': self.allow_files,
|
|
|
|
'allow_folders': self.allow_folders,
|
2008-03-20 06:29:11 +08:00
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(FilePathField, self).formfield(**defaults)
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "FilePathField"
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class FloatField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2011-08-22 08:48:53 +08:00
|
|
|
'invalid': _("'%s' value must be a float."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Floating point number")
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return float(value)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "FloatField"
|
|
|
|
|
2009-01-03 12:43:58 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return float(value)
|
|
|
|
except (TypeError, ValueError):
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2009-01-03 12:43:58 +08:00
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'form_class': forms.FloatField}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(FloatField, self).formfield(**defaults)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
|
|
|
class IntegerField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2011-08-22 08:48:53 +08:00
|
|
|
'invalid': _("'%s' value must be an integer."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return int(value)
|
|
|
|
|
2010-03-21 01:56:22 +08:00
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2011-10-13 16:11:00 +08:00
|
|
|
if ((lookup_type == 'gte' or lookup_type == 'lt')
|
|
|
|
and isinstance(value, float)):
|
|
|
|
value = math.ceil(value)
|
2010-03-21 01:56:22 +08:00
|
|
|
return super(IntegerField, self).get_prep_lookup(lookup_type, value)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "IntegerField"
|
|
|
|
|
2008-08-24 16:12:13 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return int(value)
|
|
|
|
except (TypeError, ValueError):
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2007-04-28 21:55:24 +08:00
|
|
|
defaults = {'form_class': forms.IntegerField}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(IntegerField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2009-12-17 23:10:38 +08:00
|
|
|
class BigIntegerField(IntegerField):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("Big (8 byte) integer")
|
2009-12-17 23:10:38 +08:00
|
|
|
MAX_BIGINT = 9223372036854775807
|
2011-06-14 04:15:13 +08:00
|
|
|
|
2009-12-17 23:10:38 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "BigIntegerField"
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
|
|
|
|
'max_value': BigIntegerField.MAX_BIGINT}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(BigIntegerField, self).formfield(**defaults)
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class IPAddressField(Field):
|
2007-06-26 20:59:49 +08:00
|
|
|
empty_strings_allowed = False
|
2011-06-11 21:48:24 +08:00
|
|
|
description = _("IPv4 address")
|
2011-06-14 04:15:13 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2007-08-05 13:14:46 +08:00
|
|
|
kwargs['max_length'] = 15
|
2005-08-02 05:29:52 +08:00
|
|
|
Field.__init__(self, *args, **kwargs)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "IPAddressField"
|
|
|
|
|
2007-09-16 19:38:32 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'form_class': forms.IPAddressField}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(IPAddressField, self).formfield(**defaults)
|
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
class GenericIPAddressField(Field):
|
|
|
|
empty_strings_allowed = True
|
|
|
|
description = _("IP address")
|
2011-06-13 12:31:56 +08:00
|
|
|
default_error_messages = {}
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2012-09-02 00:32:27 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, protocol='both',
|
|
|
|
unpack_ipv4=False, *args, **kwargs):
|
2011-06-11 21:48:24 +08:00
|
|
|
self.unpack_ipv4 = unpack_ipv4
|
|
|
|
self.default_validators, invalid_error_message = \
|
|
|
|
validators.ip_address_validators(protocol, unpack_ipv4)
|
|
|
|
self.default_error_messages['invalid'] = invalid_error_message
|
|
|
|
kwargs['max_length'] = 39
|
2012-09-02 00:32:27 +08:00
|
|
|
Field.__init__(self, verbose_name, name, *args, **kwargs)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "GenericIPAddressField"
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if value and ':' in value:
|
|
|
|
return clean_ipv6_address(value,
|
|
|
|
self.unpack_ipv4, self.error_messages['invalid'])
|
|
|
|
return value
|
|
|
|
|
2011-06-14 04:15:13 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
return value or None
|
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
if value and ':' in value:
|
|
|
|
try:
|
|
|
|
return clean_ipv6_address(value, self.unpack_ipv4)
|
2011-07-29 17:39:35 +08:00
|
|
|
except exceptions.ValidationError:
|
2011-06-11 21:48:24 +08:00
|
|
|
pass
|
|
|
|
return value
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'form_class': forms.GenericIPAddressField}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(GenericIPAddressField, self).formfield(**defaults)
|
|
|
|
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class NullBooleanField(Field):
|
2007-06-23 22:16:00 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2011-08-22 08:48:53 +08:00
|
|
|
'invalid': _("'%s' value must be either None, True or False."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Boolean (Either True, False or None)")
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['null'] = True
|
2010-03-10 15:41:37 +08:00
|
|
|
kwargs['blank'] = True
|
2005-08-02 05:29:52 +08:00
|
|
|
Field.__init__(self, *args, **kwargs)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "NullBooleanField"
|
|
|
|
|
2007-03-13 08:35:47 +08:00
|
|
|
def to_python(self, value):
|
2010-02-25 01:36:18 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
if value in (True, False):
|
|
|
|
return bool(value)
|
|
|
|
if value in ('None',):
|
|
|
|
return None
|
|
|
|
if value in ('t', 'True', '1'):
|
|
|
|
return True
|
|
|
|
if value in ('f', 'False', '0'):
|
|
|
|
return False
|
2012-05-31 22:46:07 +08:00
|
|
|
msg = self.error_messages['invalid'] % value
|
2011-08-22 08:48:53 +08:00
|
|
|
raise exceptions.ValidationError(msg)
|
2007-03-13 08:35:47 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
2010-10-09 16:12:50 +08:00
|
|
|
# Special-case handling for filters coming from a Web request (e.g. the
|
2008-08-29 10:40:56 +08:00
|
|
|
# admin interface). Only works for scalar values (not lists). If you're
|
|
|
|
# passing in a list, you might as well make things the right type when
|
|
|
|
# constructing the list.
|
|
|
|
if value in ('1', '0'):
|
|
|
|
value = bool(int(value))
|
2011-10-13 16:11:00 +08:00
|
|
|
return super(NullBooleanField, self).get_prep_lookup(lookup_type,
|
|
|
|
value)
|
2008-08-29 10:40:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
return bool(value)
|
|
|
|
|
2007-12-17 18:35:53 +08:00
|
|
|
def formfield(self, **kwargs):
|
2008-07-19 07:54:34 +08:00
|
|
|
defaults = {
|
|
|
|
'form_class': forms.NullBooleanField,
|
|
|
|
'required': not self.blank,
|
|
|
|
'label': capfirst(self.verbose_name),
|
|
|
|
'help_text': self.help_text}
|
2007-12-17 18:35:53 +08:00
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(NullBooleanField, self).formfield(**defaults)
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class PositiveIntegerField(IntegerField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Positive integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveIntegerField"
|
|
|
|
|
2007-09-15 10:37:07 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'min_value': 0}
|
|
|
|
defaults.update(kwargs)
|
2007-12-17 18:35:53 +08:00
|
|
|
return super(PositiveIntegerField, self).formfield(**defaults)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
|
|
|
class PositiveSmallIntegerField(IntegerField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Positive small integer")
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveSmallIntegerField"
|
|
|
|
|
2007-09-15 10:37:07 +08:00
|
|
|
def formfield(self, **kwargs):
|
|
|
|
defaults = {'min_value': 0}
|
|
|
|
defaults.update(kwargs)
|
2007-12-17 18:35:53 +08:00
|
|
|
return super(PositiveSmallIntegerField, self).formfield(**defaults)
|
2007-09-15 10:37:07 +08:00
|
|
|
|
2007-09-08 13:09:39 +08:00
|
|
|
class SlugField(CharField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Slug (up to %(max_length)s)")
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2007-08-05 13:14:46 +08:00
|
|
|
kwargs['max_length'] = kwargs.get('max_length', 50)
|
2005-08-02 05:29:52 +08:00
|
|
|
# Set db_index=True unless it's been set manually.
|
2007-04-26 21:30:48 +08:00
|
|
|
if 'db_index' not in kwargs:
|
2005-08-02 05:29:52 +08:00
|
|
|
kwargs['db_index'] = True
|
2007-09-08 13:09:39 +08:00
|
|
|
super(SlugField, self).__init__(*args, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "SlugField"
|
|
|
|
|
2008-08-23 12:59:25 +08:00
|
|
|
def formfield(self, **kwargs):
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
defaults = {'form_class': forms.SlugField}
|
2008-08-23 12:59:25 +08:00
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(SlugField, self).formfield(**defaults)
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class SmallIntegerField(IntegerField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Small integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "SmallIntegerField"
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class TextField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("Text")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "TextField"
|
|
|
|
|
2010-01-10 06:05:10 +08:00
|
|
|
def get_prep_value(self, value):
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types) or value is None:
|
2010-01-10 06:05:10 +08:00
|
|
|
return value
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2010-01-10 06:05:10 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2007-04-28 21:55:24 +08:00
|
|
|
defaults = {'widget': forms.Textarea}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(TextField, self).formfield(**defaults)
|
2007-01-11 07:34:37 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class TimeField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("'%s' value has an invalid format. It must be in "
|
|
|
|
"HH:MM[:ss[.uuuuuu]] format."),
|
|
|
|
'invalid_time': _("'%s' value has the correct format "
|
|
|
|
"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2011-11-18 21:01:06 +08:00
|
|
|
description = _("Time")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, auto_now=False,
|
|
|
|
auto_now_add=False, **kwargs):
|
2006-05-02 09:31:56 +08:00
|
|
|
self.auto_now, self.auto_now_add = auto_now, auto_now_add
|
2005-08-02 05:29:52 +08:00
|
|
|
if auto_now or auto_now_add:
|
|
|
|
kwargs['editable'] = False
|
2011-11-18 21:01:06 +08:00
|
|
|
kwargs['blank'] = True
|
2005-08-26 06:51:30 +08:00
|
|
|
Field.__init__(self, verbose_name, name, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "TimeField"
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
2009-03-10 13:24:19 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
# Not usually a good idea to pass in a datetime here (it loses
|
|
|
|
# information), but this can be a side-effect of interacting with a
|
|
|
|
# database backend (e.g. Oracle), so we'll be accommodating.
|
2010-01-10 04:02:41 +08:00
|
|
|
return value.time()
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
try:
|
|
|
|
parsed = parse_time(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
2008-07-29 13:09:29 +08:00
|
|
|
except ValueError:
|
2011-11-18 21:01:06 +08:00
|
|
|
msg = self.error_messages['invalid_time'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
|
|
|
|
|
|
|
msg = self.error_messages['invalid'] % value
|
|
|
|
raise exceptions.ValidationError(msg)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2005-08-10 11:50:46 +08:00
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2006-05-30 01:08:58 +08:00
|
|
|
value = datetime.datetime.now().time()
|
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
|
|
|
return super(TimeField, self).pre_save(model_instance, add)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
return self.to_python(value)
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2008-07-29 13:09:29 +08:00
|
|
|
# Casts times into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
return connection.ops.value_to_db_time(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2005-11-26 05:20:09 +08:00
|
|
|
val = self._get_val_from_obj(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return '' if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2007-04-28 21:55:24 +08:00
|
|
|
defaults = {'form_class': forms.TimeField}
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2007-04-28 21:55:24 +08:00
|
|
|
return super(TimeField, self).formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2007-01-09 04:28:31 +08:00
|
|
|
class URLField(CharField):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("URL")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2012-03-31 21:55:03 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, **kwargs):
|
2007-08-05 13:14:46 +08:00
|
|
|
kwargs['max_length'] = kwargs.get('max_length', 200)
|
2007-01-09 04:28:31 +08:00
|
|
|
CharField.__init__(self, verbose_name, name, **kwargs)
|
2012-03-31 21:55:03 +08:00
|
|
|
self.validators.append(validators.URLValidator())
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2010-08-05 11:59:20 +08:00
|
|
|
def formfield(self, **kwargs):
|
2011-10-13 16:11:00 +08:00
|
|
|
# As with CharField, this will cause URL validation to be performed
|
|
|
|
# twice.
|
2010-08-05 11:59:20 +08:00
|
|
|
defaults = {
|
|
|
|
'form_class': forms.URLField,
|
|
|
|
}
|
|
|
|
defaults.update(kwargs)
|
|
|
|
return super(URLField, self).formfield(**defaults)
|
2012-12-14 05:11:06 +08:00
|
|
|
|
|
|
|
class BinaryField(Field):
|
|
|
|
description = _("Raw binary data")
|
2013-03-06 15:28:12 +08:00
|
|
|
empty_values = [None, b'']
|
2012-12-14 05:11:06 +08:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs['editable'] = False
|
|
|
|
super(BinaryField, self).__init__(*args, **kwargs)
|
|
|
|
if self.max_length is not None:
|
|
|
|
self.validators.append(validators.MaxLengthValidator(self.max_length))
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "BinaryField"
|
|
|
|
|
|
|
|
def get_default(self):
|
|
|
|
if self.has_default() and not callable(self.default):
|
|
|
|
return self.default
|
|
|
|
default = super(BinaryField, self).get_default()
|
|
|
|
if default == '':
|
|
|
|
return b''
|
|
|
|
return default
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
value = super(BinaryField, self
|
|
|
|
).get_db_prep_value(value, connection, prepared)
|
|
|
|
if value is not None:
|
|
|
|
return connection.Database.Binary(value)
|
|
|
|
return value
|
2012-12-15 07:26:08 +08:00
|
|
|
|
|
|
|
def value_to_string(self, obj):
|
|
|
|
"""Binary data is serialized as base64"""
|
|
|
|
return b64encode(force_bytes(self._get_val_from_obj(obj))).decode('ascii')
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
# If it's a string, it should be base64-encoded data
|
|
|
|
if isinstance(value, six.text_type):
|
|
|
|
return six.memoryview(b64decode(force_bytes(value)))
|
|
|
|
return value
|