1
0
mirror of https://github.com/django/django.git synced 2025-10-24 22:26:08 +00:00

MERGED NEW-ADMIN BRANCH (except for po/mo files, which will come in a separate commit)

git-svn-id: http://code.djangoproject.com/svn/django/trunk@1434 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty
2005-11-25 21:20:09 +00:00
parent 4fe5c9b7ee
commit 9dda4abee1
30 changed files with 2046 additions and 1109 deletions

View File

@@ -90,15 +90,7 @@ class Manipulator:
expected to deal with invalid input.
"""
for field in self.fields:
if new_data.has_key(field.field_name):
new_data.setlist(field.field_name,
[field.__class__.html2python(data) for data in new_data.getlist(field.field_name)])
else:
try:
# individual fields deal with None values themselves
new_data.setlist(field.field_name, [field.__class__.html2python(None)])
except EmptyValue:
new_data.setlist(field.field_name, [])
field.convert_post_data(new_data)
class FormWrapper:
"""
@@ -106,24 +98,36 @@ class FormWrapper:
This allows dictionary-style lookups of formfields. It also handles feeding
prepopulated data and validation error messages to the formfield objects.
"""
def __init__(self, manipulator, data, error_dict):
def __init__(self, manipulator, data, error_dict, edit_inline=True):
self.manipulator, self.data = manipulator, data
self.error_dict = error_dict
self._inline_collections = None
self.edit_inline = edit_inline
def __repr__(self):
return repr(self.data)
return repr(self.__dict__)
def __getitem__(self, key):
for field in self.manipulator.fields:
if field.field_name == key:
if hasattr(field, 'requires_data_list') and hasattr(self.data, 'getlist'):
data = self.data.getlist(field.field_name)
else:
data = self.data.get(field.field_name, None)
if data is None:
data = ''
data = field.extract_data(self.data)
return FormFieldWrapper(field, data, self.error_dict.get(field.field_name, []))
raise KeyError
if self.edit_inline:
self.fill_inline_collections()
for inline_collection in self._inline_collections:
if inline_collection.name == key:
return inline_collection
raise KeyError, "Could not find Formfield or InlineObjectCollection named %r" % key
def fill_inline_collections(self):
if not self._inline_collections:
ic = []
related_objects = self.manipulator.get_related_objects()
for rel_obj in related_objects:
data = rel_obj.extract_data(self.data)
inline_collection = InlineObjectCollection(self.manipulator, rel_obj, data, self.error_dict)
ic.append(inline_collection)
self._inline_collections = ic
def has_errors(self):
return self.error_dict != {}
@@ -166,6 +170,9 @@ class FormFieldWrapper:
else:
return ''
def get_id(self):
return self.formfield.get_id()
class FormFieldCollection(FormFieldWrapper):
"A utility class that gives the template access to a dict of FormFieldWrappers"
def __init__(self, formfield_dict):
@@ -185,9 +192,66 @@ class FormFieldCollection(FormFieldWrapper):
"Returns list of all errors in this collection's formfields"
errors = []
for field in self.formfield_dict.values():
errors.extend(field.errors())
if hasattr(field, 'errors'):
errors.extend(field.errors())
return errors
def has_errors(self):
return bool(len(self.errors()))
def html_combined_error_list(self):
return ''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')])
class InlineObjectCollection:
"An object that acts like a list of form field collections."
def __init__(self, parent_manipulator, rel_obj, data, errors):
self.parent_manipulator = parent_manipulator
self.rel_obj = rel_obj
self.data = data
self.errors = errors
self._collections = None
self.name = rel_obj.name
def __len__(self):
self.fill()
return self._collections.__len__()
def __getitem__(self, k):
self.fill()
return self._collections.__getitem__(k)
def __setitem__(self, k, v):
self.fill()
return self._collections.__setitem__(k,v)
def __delitem__(self, k):
self.fill()
return self._collections.__delitem__(k)
def __iter__(self):
self.fill()
return self._collections.__iter__()
def fill(self):
if self._collections:
return
else:
var_name = self.rel_obj.opts.object_name.lower()
wrapper = []
orig = hasattr(self.parent_manipulator, 'original_object') and self.parent_manipulator.original_object or None
orig_list = self.rel_obj.get_list(orig)
for i, instance in enumerate(orig_list):
collection = {'original': instance}
for f in self.rel_obj.editable_fields():
for field_name in f.get_manipulator_field_names(''):
full_field_name = '%s.%d.%s' % (var_name, i, field_name)
field = self.parent_manipulator[full_field_name]
data = field.extract_data(self.data)
errors = self.errors.get(full_field_name, [])
collection[field_name] = FormFieldWrapper(field, data, errors)
wrapper.append(FormFieldCollection(collection))
self._collections = wrapper
class FormField:
"""Abstract class representing a form field.
@@ -220,6 +284,37 @@ class FormField:
def render(self, data):
raise NotImplementedError
def get_member_name(self):
if hasattr(self, 'member_name'):
return self.member_name
else:
return self.field_name
def extract_data(self, data_dict):
if hasattr(self, 'requires_data_list') and hasattr(data_dict, 'getlist'):
data = data_dict.getlist(self.get_member_name())
else:
data = data_dict.get(self.get_member_name(), None)
if data is None:
data = ''
return data
def convert_post_data(self, new_data):
name = self.get_member_name()
if new_data.has_key(self.field_name):
d = new_data.getlist(self.field_name)
try:
converted_data = [self.__class__.html2python(data) for data in d]
except ValueError:
converted_data = d
new_data.setlist(name, converted_data)
else:
try:
# individual fields deal with None values themselves
new_data.setlist(name, [self.__class__.html2python(None)])
except EmptyValue:
new_data.setlist(name, [])
def get_id(self):
"Returns the HTML 'id' attribute for this form field."
return FORM_FIELD_ID_PREFIX + self.field_name
@@ -313,11 +408,13 @@ class CheckboxField(FormField):
html2python = staticmethod(html2python)
class SelectField(FormField):
def __init__(self, field_name, choices=[], size=1, is_required=False, validator_list=[]):
def __init__(self, field_name, choices=[], size=1, is_required=False, validator_list=[], member_name=None):
self.field_name = field_name
# choices is a list of (value, human-readable key) tuples because order matters
self.choices, self.size, self.is_required = choices, size, is_required
self.validator_list = [self.isValidChoice] + validator_list
if member_name != None:
self.member_name = member_name
def render(self, data):
output = ['<select id="%s" class="v%s%s" name="%s" size="%s">' % \
@@ -347,12 +444,14 @@ class NullSelectField(SelectField):
html2python = staticmethod(html2python)
class RadioSelectField(FormField):
def __init__(self, field_name, choices=[], ul_class='', is_required=False, validator_list=[]):
def __init__(self, field_name, choices=[], ul_class='', is_required=False, validator_list=[], member_name=None):
self.field_name = field_name
# choices is a list of (value, human-readable key) tuples because order matters
self.choices, self.is_required = choices, is_required
self.validator_list = [self.isValidChoice] + validator_list
self.ul_class = ul_class
if member_name != None:
self.member_name = member_name
def render(self, data):
"""
@@ -483,8 +582,8 @@ class CheckboxSelectMultipleField(SelectMultipleField):
checked_html = ' checked="checked"'
field_name = '%s%s' % (self.field_name, value)
output.append('<li><input type="checkbox" id="%s" class="v%s" name="%s"%s /> <label for="%s">%s</label></li>' % \
(self.get_id(), self.__class__.__name__, field_name, checked_html,
self.get_id(), choice))
(self.get_id() + value , self.__class__.__name__, field_name, checked_html,
self.get_id() + value, choice))
output.append('</ul>')
return '\n'.join(output)
@@ -528,8 +627,10 @@ class ImageUploadField(FileUploadField):
####################
class IntegerField(TextField):
def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=[]):
def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=[], member_name=None):
validator_list = [self.isInteger] + validator_list
if member_name is not None:
self.member_name = member_name
TextField.__init__(self, field_name, length, maxlength, is_required, validator_list)
def isInteger(self, field_data, all_data):
@@ -784,6 +885,11 @@ class CommaSeparatedIntegerField(TextField):
except validators.ValidationError, e:
raise validators.CriticalValidationError, e.messages
class RawIdAdminField(CommaSeparatedIntegerField):
def html2python(data):
return data.split(',');
html2python = classmethod(html2python)
class XMLLargeTextField(LargeTextField):
"""
A LargeTextField with an XML validator. The schema_path argument is the

View File

@@ -670,12 +670,12 @@ def get_validation_errors(outfile):
e.add(opts, '"ordering" refers to "%s", a field that doesn\'t exist.' % field_name)
# Check core=True, if needed.
for rel_opts, rel_field in opts.get_inline_related_objects():
for related in opts.get_followed_related_objects():
try:
for f in rel_opts.fields:
for f in related.opts.fields:
if f.core:
raise StopIteration
e.add(rel_opts, "At least one field in %s should have core=True, because it's being edited inline by %s.%s." % (rel_opts.object_name, opts.module_name, opts.object_name))
e.add(related.opts, "At least one field in %s should have core=True, because it's being edited inline by %s.%s." % (related.opts.object_name, opts.module_name, opts.object_name))
except StopIteration:
pass

View File

@@ -148,6 +148,140 @@ class FieldDoesNotExist(Exception):
class BadKeywordArguments(Exception):
pass
class BoundRelatedObject(object):
def __init__(self, related_object, field_mapping, original):
self.relation = related_object
self.field_mappings = field_mapping[related_object.opts.module_name]
def template_name(self):
raise NotImplementedError
def __repr__(self):
return repr(self.__dict__)
class RelatedObject(object):
def __init__(self, parent_opts, opts, field):
self.parent_opts = parent_opts
self.opts = opts
self.field = field
self.edit_inline = field.rel.edit_inline
self.name = opts.module_name
self.var_name = opts.object_name.lower()
def flatten_data(self, follow, obj=None):
new_data = {}
rel_instances = self.get_list(obj)
for i, rel_instance in enumerate(rel_instances):
instance_data = {}
for f in self.opts.fields + self.opts.many_to_many:
# TODO: Fix for recursive manipulators.
fol = follow.get(f.name, None)
if fol:
field_data = f.flatten_data(fol, rel_instance)
for name, value in field_data.items():
instance_data['%s.%d.%s' % (self.var_name, i, name)] = value
new_data.update(instance_data)
return new_data
def extract_data(self, data):
"""
Pull out the data meant for inline objects of this class,
i.e. anything starting with our module name.
"""
return data # TODO
def get_list(self, parent_instance=None):
"Get the list of this type of object from an instance of the parent class."
if parent_instance != None:
func_name = 'get_%s_list' % self.get_method_name_part()
func = getattr(parent_instance, func_name)
list = func()
count = len(list) + self.field.rel.num_extra_on_change
if self.field.rel.min_num_in_admin:
count = max(count, self.field.rel.min_num_in_admin)
if self.field.rel.max_num_in_admin:
count = min(count, self.field.rel.max_num_in_admin)
change = count - len(list)
if change > 0:
return list + [None for _ in range(change)]
if change < 0:
return list[:change]
else: # Just right
return list
else:
return [None for _ in range(self.field.rel.num_in_admin)]
def editable_fields(self):
"Get the fields in this class that should be edited inline."
return [f for f in self.opts.fields + self.opts.many_to_many if f.editable and f != self.field]
def get_follow(self, override=None):
if isinstance(override, bool):
if override:
over = {}
else:
return None
else:
if override:
over = override.copy()
elif self.edit_inline:
over = {}
else:
return None
over[self.field.name] = False
return self.opts.get_follow(over)
def __repr__(self):
return "<RelatedObject: %s related to %s>" % ( self.name, self.field.name)
def get_manipulator_fields(self, opts, manipulator, change, follow):
# TODO: Remove core fields stuff.
if change:
meth_name = 'get_%s_count' % self.get_method_name_part()
count = getattr(manipulator.original_object, meth_name)()
count += self.field.rel.num_extra_on_change
if self.field.rel.min_num_in_admin:
count = max(count, self.field.rel.min_num_in_admin)
if self.field.rel.max_num_in_admin:
count = min(count, self.field.rel.max_num_in_admin)
else:
count = self.field.rel.num_in_admin
fields = []
for i in range(count):
for f in self.opts.fields + self.opts.many_to_many:
if follow.get(f.name, False):
prefix = '%s.%d.' % (self.var_name, i)
fields.extend(f.get_manipulator_fields(self.opts, manipulator, change, name_prefix=prefix, rel=True))
return fields
def bind(self, field_mapping, original, bound_related_object_class=BoundRelatedObject):
return bound_related_object_class(self, field_mapping, original)
def get_method_name_part(self):
# This method encapsulates the logic that decides what name to give a
# method that retrieves related many-to-one objects. Usually it just
# uses the lower-cased object_name, but if the related object is in
# another app, its app_label is appended.
#
# Examples:
#
# # Normal case -- a related object in the same app.
# # This method returns "choice".
# Poll.get_choice_list()
#
# # A related object in a different app.
# # This method returns "lcom_bestofaward".
# Place.get_lcom_bestofaward_list() # "lcom_bestofaward"
rel_obj_name = self.field.rel.related_name or self.opts.object_name.lower()
if self.parent_opts.app_label != self.opts.app_label:
rel_obj_name = '%s_%s' % (self.opts.app_label, rel_obj_name)
return rel_obj_name
class Options:
def __init__(self, module_name='', verbose_name='', verbose_name_plural='', db_table='',
fields=None, ordering=None, unique_together=None, admin=None, has_related_links=False,
@@ -268,26 +402,6 @@ class Options:
def get_delete_permission(self):
return 'delete_%s' % self.object_name.lower()
def get_rel_object_method_name(self, rel_opts, rel_field):
# This method encapsulates the logic that decides what name to give a
# method that retrieves related many-to-one objects. Usually it just
# uses the lower-cased object_name, but if the related object is in
# another app, its app_label is appended.
#
# Examples:
#
# # Normal case -- a related object in the same app.
# # This method returns "choice".
# Poll.get_choice_list()
#
# # A related object in a different app.
# # This method returns "lcom_bestofaward".
# Place.get_lcom_bestofaward_list() # "lcom_bestofaward"
rel_obj_name = rel_field.rel.related_name or rel_opts.object_name.lower()
if self.app_label != rel_opts.app_label:
rel_obj_name = '%s_%s' % (rel_opts.app_label, rel_obj_name)
return rel_obj_name
def get_all_related_objects(self):
try: # Try the cache first.
return self._all_related_objects
@@ -298,7 +412,7 @@ class Options:
for klass in mod._MODELS:
for f in klass._meta.fields:
if f.rel and self == f.rel.to:
rel_objs.append((klass._meta, f))
rel_objs.append(RelatedObject(self, klass._meta, f))
if self.has_related_links:
# Manually add RelatedLink objects, which are a special case.
relatedlinks = get_module('relatedlinks', 'relatedlinks')
@@ -312,12 +426,31 @@ class Options:
'content_type__package__label__exact': self.app_label,
'content_type__python_module_name__exact': self.module_name,
})
rel_objs.append((relatedlinks.RelatedLink._meta, link_field))
rel_objs.append(RelatedObject(self, relatedlinks.RelatedLink._meta, link_field))
self._all_related_objects = rel_objs
return rel_objs
def get_inline_related_objects(self):
return [(a, b) for a, b in self.get_all_related_objects() if b.rel.edit_inline]
def get_followed_related_objects(self, follow=None):
if follow == None:
follow = self.get_follow()
return [f for f in self.get_all_related_objects() if follow.get(f.name, None)]
def get_data_holders(self, follow=None):
if follow == None:
follow = self.get_follow()
return [f for f in self.fields + self.many_to_many + self.get_all_related_objects() if follow.get(f.name, None)]
def get_follow(self, override=None):
follow = {}
for f in self.fields + self.many_to_many + self.get_all_related_objects():
if override and override.has_key(f.name):
child_override = override[f.name]
else:
child_override = None
fol = f.get_follow(child_override)
if fol:
follow[f.name] = fol
return follow
def get_all_related_many_to_many_objects(self):
module_list = get_installed_model_modules()
@@ -327,7 +460,7 @@ class Options:
try:
for f in klass._meta.many_to_many:
if f.rel and self == f.rel.to:
rel_objs.append((klass._meta, f))
rel_objs.append(RelatedObject(self, klass._meta, f))
raise StopIteration
except StopIteration:
continue
@@ -345,11 +478,12 @@ class Options:
self._ordered_objects = objects
return self._ordered_objects
def has_field_type(self, field_type):
def has_field_type(self, field_type, follow=None):
"""
Returns True if this object's admin form has at least one of the given
field_type (e.g. FileField).
"""
# TODO: follow
if not hasattr(self, '_field_types'):
self._field_types = {}
if not self._field_types.has_key(field_type):
@@ -359,8 +493,8 @@ class Options:
if isinstance(f, field_type):
raise StopIteration
# Failing that, check related fields.
for rel_obj, rel_field in self.get_inline_related_objects():
for f in rel_obj.fields:
for related in self.get_followed_related_objects(follow):
for f in related.opts.fields:
if isinstance(f, field_type):
raise StopIteration
except StopIteration:
@@ -597,6 +731,7 @@ class ModelBase(type):
new_mod.get_latest = curry(function_get_latest, opts, new_class, does_not_exist_exception)
for f in opts.fields:
#TODO : change this into a virtual function so that user defined fields will be able to add methods to module or class.
if f.choices:
# Add "get_thingie_display" method to get human-readable value.
func = curry(method_get_display_value, f)
@@ -720,12 +855,9 @@ class ModelBase(type):
old_app._MODELS[i] = new_class
# Replace all relationships to the old class with
# relationships to the new one.
for rel_opts, rel_field in model._meta.get_all_related_objects():
rel_field.rel.to = opts
for rel_opts, rel_field in model._meta.get_all_related_many_to_many_objects():
rel_field.rel.to = opts
for related in model._meta.get_all_related_objects() + model._meta.get_all_related_many_to_many_objects():
related.field.rel.to = opts
break
return new_class
class Model:
@@ -826,9 +958,9 @@ def method_delete(opts, self):
if hasattr(self, '_pre_delete'):
self._pre_delete()
cursor = db.db.cursor()
for rel_opts, rel_field in opts.get_all_related_objects():
rel_opts_name = opts.get_rel_object_method_name(rel_opts, rel_field)
if isinstance(rel_field.rel, OneToOne):
for related in opts.get_all_related_objects():
rel_opts_name = related.get_method_name_part()
if isinstance(related.field.rel, OneToOne):
try:
sub_obj = getattr(self, 'get_%s' % rel_opts_name)()
except ObjectDoesNotExist:
@@ -838,9 +970,9 @@ def method_delete(opts, self):
else:
for sub_obj in getattr(self, 'get_%s_list' % rel_opts_name)():
sub_obj.delete()
for rel_opts, rel_field in opts.get_all_related_many_to_many_objects():
for related in opts.get_all_related_many_to_many_objects():
cursor.execute("DELETE FROM %s WHERE %s=%%s" % \
(db.db.quote_name(rel_field.get_m2m_db_table(rel_opts)),
(db.db.quote_name(related.field.get_m2m_db_table(related.opts)),
db.db.quote_name(self._meta.object_name.lower() + '_id')), [getattr(self, opts.pk.attname)])
for f in opts.many_to_many:
cursor.execute("DELETE FROM %s WHERE %s=%%s" % \
@@ -1474,6 +1606,8 @@ def get_manipulator(opts, klass, extra_methods, add=False, change=False):
man.__module__ = MODEL_PREFIX + '.' + opts.module_name # Set this explicitly, as above.
man.__init__ = curry(manipulator_init, opts, add, change)
man.save = curry(manipulator_save, opts, klass, add, change)
man.get_related_objects = curry(manipulator_get_related_objects, opts, klass, add, change)
man.flatten_data = curry(manipulator_flatten_data, opts, klass, add, change)
for field_name_list in opts.unique_together:
setattr(man, 'isUnique%s' % '_'.join(field_name_list), curry(manipulator_validator_unique_together, field_name_list, opts))
for f in opts.fields:
@@ -1487,7 +1621,9 @@ def get_manipulator(opts, klass, extra_methods, add=False, change=False):
setattr(man, k, v)
return man
def manipulator_init(opts, add, change, self, obj_key=None):
def manipulator_init(opts, add, change, self, obj_key=None, follow=None):
self.follow = opts.get_follow(follow)
if change:
assert obj_key is not None, "ChangeManipulator.__init__() must be passed obj_key parameter."
self.obj_key = obj_key
@@ -1511,40 +1647,37 @@ def manipulator_init(opts, add, change, self, obj_key=None):
else:
raise
self.fields = []
for f in opts.fields + opts.many_to_many:
if f.editable and not (f.primary_key and change) and (not f.rel or not f.rel.edit_inline):
if self.follow.get(f.name, False):
self.fields.extend(f.get_manipulator_fields(opts, self, change))
# Add fields for related objects.
for rel_opts, rel_field in opts.get_inline_related_objects():
if change:
count = getattr(self.original_object, 'get_%s_count' % opts.get_rel_object_method_name(rel_opts, rel_field))()
count += rel_field.rel.num_extra_on_change
if rel_field.rel.min_num_in_admin:
count = max(count, rel_field.rel.min_num_in_admin)
if rel_field.rel.max_num_in_admin:
count = min(count, rel_field.rel.max_num_in_admin)
else:
count = rel_field.rel.num_in_admin
for f in rel_opts.fields + rel_opts.many_to_many:
if f.editable and f != rel_field and (not f.primary_key or (f.primary_key and change)):
for i in range(count):
self.fields.extend(f.get_manipulator_fields(rel_opts, self, change, name_prefix='%s.%d.' % (rel_opts.object_name.lower(), i), rel=True))
for f in opts.get_all_related_objects():
if self.follow.get(f.name, False):
fol = self.follow[f.name]
self.fields.extend(f.get_manipulator_fields(opts, self, change, fol))
# Add field for ordering.
if change and opts.get_ordered_objects():
self.fields.append(formfields.CommaSeparatedIntegerField(field_name="order_"))
def manipulator_save(opts, klass, add, change, self, new_data):
# TODO: big cleanup when core fields go -> use recursive manipulators.
from django.utils.datastructures import DotExpandedDict
params = {}
for f in opts.fields:
# Fields with auto_now_add are another special case; they should keep
# their original value in the change stage.
if change and getattr(f, 'auto_now_add', False):
params[f.attname] = getattr(self.original_object, f.attname)
# Fields with auto_now_add should keep their original value in the change stage.
auto_now_add = change and getattr(f, 'auto_now_add', False)
if self.follow.get(f.name, None) and not auto_now_add:
param = f.get_manipulator_new_data(new_data)
else:
params[f.attname] = f.get_manipulator_new_data(new_data)
if change:
param = getattr(self.original_object, f.attname)
else:
param = f.get_default()
params[f.attname] = param
if change:
params[opts.pk.attname] = self.obj_key
@@ -1567,101 +1700,116 @@ def manipulator_save(opts, klass, add, change, self, new_data):
# Save many-to-many objects. Example: Poll.set_sites()
for f in opts.many_to_many:
if not f.rel.edit_inline:
was_changed = getattr(new_object, 'set_%s' % f.name)(new_data.getlist(f.name))
if change and was_changed:
self.fields_changed.append(f.verbose_name)
if self.follow.get(f.name, None):
if not f.rel.edit_inline:
was_changed = getattr(new_object, 'set_%s' % f.name)(new_data.getlist(f.name))
if change and was_changed:
self.fields_changed.append(f.verbose_name)
expanded_data = DotExpandedDict(new_data.data)
# Save many-to-one objects. Example: Add the Choice objects for a Poll.
for rel_opts, rel_field in opts.get_inline_related_objects():
for related in opts.get_all_related_objects():
# Create obj_list, which is a DotExpandedDict such as this:
# [('0', {'id': ['940'], 'choice': ['This is the first choice']}),
# ('1', {'id': ['941'], 'choice': ['This is the second choice']}),
# ('2', {'id': [''], 'choice': ['']})]
obj_list = DotExpandedDict(new_data.data)[rel_opts.object_name.lower()].items()
obj_list.sort(lambda x, y: cmp(int(x[0]), int(y[0])))
params = {}
child_follow = self.follow.get(related.name, None)
# For each related item...
for _, rel_new_data in obj_list:
if child_follow:
obj_list = expanded_data[related.var_name].items()
obj_list.sort(lambda x, y: cmp(int(x[0]), int(y[0])))
params = {}
# Keep track of which core=True fields were provided.
# If all core fields were given, the related object will be saved.
# If none of the core fields were given, the object will be deleted.
# If some, but not all, of the fields were given, the validator would
# have caught that.
all_cores_given, all_cores_blank = True, True
# Get a reference to the old object. We'll use it to compare the
# old to the new, to see which fields have changed.
if change:
# For each related item...
for _, rel_new_data in obj_list:
# Keep track of which core=True fields were provided.
# If all core fields were given, the related object will be saved.
# If none of the core fields were given, the object will be deleted.
# If some, but not all, of the fields were given, the validator would
# have caught that.
all_cores_given, all_cores_blank = True, True
# Get a reference to the old object. We'll use it to compare the
# old to the new, to see which fields have changed.
old_rel_obj = None
if rel_new_data[rel_opts.pk.name][0]:
try:
old_rel_obj = getattr(self.original_object, 'get_%s' % opts.get_rel_object_method_name(rel_opts, rel_field))(**{'%s__exact' % rel_opts.pk.name: rel_new_data[rel_opts.pk.attname][0]})
except ObjectDoesNotExist:
pass
for f in rel_opts.fields:
if f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) in (None, ''):
all_cores_given = False
elif f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) not in (None, ''):
all_cores_blank = False
# If this field isn't editable, give it the same value it had
# previously, according to the given ID. If the ID wasn't
# given, use a default value. FileFields are also a special
# case, because they'll be dealt with later.
if change and (isinstance(f, FileField) or not f.editable):
if rel_new_data.get(rel_opts.pk.attname, False) and rel_new_data[rel_opts.pk.attname][0]:
params[f.attname] = getattr(old_rel_obj, f.attname)
else:
params[f.attname] = f.get_default()
elif f == rel_field:
params[f.attname] = getattr(new_object, rel_field.rel.field_name)
elif add and isinstance(f, AutoField):
params[f.attname] = None
else:
params[f.attname] = f.get_manipulator_new_data(rel_new_data, rel=True)
# Related links are a special case, because we have to
# manually set the "content_type_id" and "object_id" fields.
if opts.has_related_links and rel_opts.module_name == 'relatedlinks':
contenttypes_mod = get_module('core', 'contenttypes')
params['content_type_id'] = contenttypes_mod.get_object(package__label__exact=opts.app_label, python_module_name__exact=opts.module_name).id
params['object_id'] = new_object.id
# Create the related item.
new_rel_obj = rel_opts.get_model_module().Klass(**params)
# If all the core fields were provided (non-empty), save the item.
if all_cores_given:
new_rel_obj.save()
# Save any uploaded files.
for f in rel_opts.fields:
if isinstance(f, FileField) and rel_new_data.get(f.attname, False):
f.save_file(rel_new_data, new_rel_obj, change and old_rel_obj or None, old_rel_obj is not None, rel=True)
# Calculate whether any fields have changed.
if change:
if not old_rel_obj: # This object didn't exist before.
self.fields_added.append('%s "%r"' % (rel_opts.verbose_name, new_rel_obj))
if rel_new_data[related.opts.pk.name][0]:
try:
old_rel_obj = getattr(self.original_object, 'get_%s' % related.get_method_name_part() )(**{'%s__exact' % related.opts.pk.name: rel_new_data[related.opts.pk.attname][0]})
except ObjectDoesNotExist:
pass
for f in related.opts.fields:
if f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) in (None, ''):
all_cores_given = False
elif f.core and not isinstance(f, FileField) and f.get_manipulator_new_data(rel_new_data, rel=True) not in (None, ''):
all_cores_blank = False
# If this field isn't editable, give it the same value it had
# previously, according to the given ID. If the ID wasn't
# given, use a default value. FileFields are also a special
# case, because they'll be dealt with later.
if f == related.field:
param = getattr(new_object, related.field.rel.field_name)
elif add and isinstance(f, AutoField):
param = None
elif change and (isinstance(f, FileField) or not child_follow.get(f.name, None)):
if old_rel_obj:
param = getattr(old_rel_obj, f.column)
else:
param = f.get_default()
else:
for f in rel_opts.fields:
if not f.primary_key and f != rel_field and str(getattr(old_rel_obj, f.attname)) != str(getattr(new_rel_obj, f.attname)):
self.fields_changed.append('%s for %s "%r"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))
param = f.get_manipulator_new_data(rel_new_data, rel=True)
if param != None:
params[f.attname] = param
# Save many-to-many objects.
for f in rel_opts.many_to_many:
if not f.rel.edit_inline:
was_changed = getattr(new_rel_obj, 'set_%s' % f.name)(rel_new_data[f.attname])
if change and was_changed:
self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, rel_opts.verbose_name, new_rel_obj))
# If, in the change stage, all of the core fields were blank and
# the primary key (ID) was provided, delete the item.
if change and all_cores_blank and rel_new_data.has_key(rel_opts.pk.attname) and rel_new_data[rel_opts.pk.attname][0]:
new_rel_obj.delete()
self.fields_deleted.append('%s "%r"' % (rel_opts.verbose_name, old_rel_obj))
# Related links are a special case, because we have to
# manually set the "content_type_id" and "object_id" fields.
if opts.has_related_links and related.opts.module_name == 'relatedlinks':
contenttypes_mod = get_module('core', 'contenttypes')
params['content_type_id'] = contenttypes_mod.get_object(package__label__exact=opts.app_label, python_module_name__exact=opts.module_name).id
params['object_id'] = new_object.id
# Create the related item.
new_rel_obj = related.opts.get_model_module().Klass(**params)
# If all the core fields were provided (non-empty), save the item.
if all_cores_given:
new_rel_obj.save()
# Save any uploaded files.
for f in related.opts.fields:
if child_follow.get(f.name, None):
if isinstance(f, FileField) and rel_new_data.get(f.name, False):
f.save_file(rel_new_data, new_rel_obj, change and old_rel_obj or None, old_rel_obj is not None, rel=True)
# Calculate whether any fields have changed.
if change:
if not old_rel_obj: # This object didn't exist before.
self.fields_added.append('%s "%s"' % (related.opts.verbose_name, new_rel_obj))
else:
for f in related.opts.fields:
if not f.primary_key and f != related.field and str(getattr(old_rel_obj, f.attname)) != str(getattr(new_rel_obj, f.attname)):
self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, related.opts.verbose_name, new_rel_obj))
# Save many-to-many objects.
for f in related.opts.many_to_many:
if child_follow.get(f.name, None) and not f.rel.edit_inline:
was_changed = getattr(new_rel_obj, 'set_%s' % f.name)(rel_new_data[f.attname])
if change and was_changed:
self.fields_changed.append('%s for %s "%s"' % (f.verbose_name, related.opts.verbose_name, new_rel_obj))
# If, in the change stage, all of the core fields were blank and
# the primary key (ID) was provided, delete the item.
if change and all_cores_blank and old_rel_obj:
new_rel_obj.delete()
self.fields_deleted.append('%s "%s"' % (related.opts.verbose_name, old_rel_obj))
# Save the order, if applicable.
if change and opts.get_ordered_objects():
@@ -1670,6 +1818,17 @@ def manipulator_save(opts, klass, add, change, self, new_data):
getattr(new_object, 'set_%s_order' % rel_opts.object_name.lower())(order)
return new_object
def manipulator_get_related_objects(opts, klass, add, change, self):
return opts.get_followed_related_objects(self.follow)
def manipulator_flatten_data(opts, klass, add, change, self):
new_data = {}
obj = change and self.original_object or None
for f in opts.get_data_holders(self.follow):
fol = self.follow.get(f.name)
new_data.update(f.flatten_data(fol, obj))
return new_data
def manipulator_validator_unique_together(field_name_list, opts, self, field_data, all_data):
from django.utils.text import get_text_list
field_list = [opts.get_field(field_name) for field_name in field_name_list]
@@ -1678,6 +1837,9 @@ def manipulator_validator_unique_together(field_name_list, opts, self, field_dat
else:
kwargs = {'%s__iexact' % field_name_list[0]: field_data}
for f in field_list[1:]:
# This is really not going to work for fields that have different
# form fields, e.g. DateTime.
# This validation needs to occur after html2python to be effective.
field_val = all_data.get(f.attname, None)
if field_val is None:
# This will be caught by another validator, assuming the field

View File

@@ -59,6 +59,24 @@ def manipulator_validator_unique(f, opts, self, field_data, all_data):
return
raise validators.ValidationError, _("%(optname)s with this %(fieldname)s already exists.") % {'optname': capfirst(opts.verbose_name), 'fieldname': f.verbose_name}
class BoundField(object):
def __init__(self, field, field_mapping, original):
self.field = field
self.original = original
self.form_fields = self.resolve_form_fields(field_mapping)
def resolve_form_fields(self, field_mapping):
return [field_mapping[name] for name in self.field.get_manipulator_field_names('')]
def as_field_list(self):
return [self.field]
def original_value(self):
if self.original:
return self.original.__dict__[self.field.column]
def __repr__(self):
return "BoundField:(%s, %s)" % (self.field.name, self.form_fields)
# A guide to Field parameters:
#
@@ -185,7 +203,7 @@ class Field(object):
if hasattr(self.default, '__get_value__'):
return self.default.__get_value__()
return self.default
if self.null:
if not self.empty_strings_allowed or self.null:
return None
return ""
@@ -207,28 +225,28 @@ class Field(object):
if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter.
params['maxlength'] = self.maxlength
if isinstance(self.rel, ManyToOne):
params['member_name'] = name_prefix + self.attname
if self.rel.raw_id_admin:
field_objs = self.get_manipulator_field_objs()
params['validator_list'].append(curry(manipulator_valid_rel_key, self, manipulator))
else:
if self.radio_admin:
field_objs = [formfields.RadioSelectField]
params['choices'] = self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE)
params['ul_class'] = get_ul_class(self.radio_admin)
else:
if self.null:
field_objs = [formfields.NullSelectField]
else:
field_objs = [formfields.SelectField]
params['choices'] = self.get_choices()
params['choices'] = self.get_choices_default()
elif self.choices:
if self.radio_admin:
field_objs = [formfields.RadioSelectField]
params['choices'] = self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE)
params['ul_class'] = get_ul_class(self.radio_admin)
else:
field_objs = [formfields.SelectField]
params['choices'] = self.get_choices()
params['choices'] = self.get_choices_default()
else:
field_objs = self.get_manipulator_field_objs()
@@ -294,7 +312,37 @@ class Field(object):
if self.choices:
return first_choice + list(self.choices)
rel_obj = self.rel.to
return first_choice + [(getattr(x, rel_obj.pk.attname), repr(x)) for x in rel_obj.get_model_module().get_list(**self.rel.limit_choices_to)]
return first_choice + [(getattr(x, rel_obj.pk.attname), str(x))
for x in rel_obj.get_model_module().get_list(**self.rel.limit_choices_to)]
def get_choices_default(self):
if(self.radio_admin):
return self.get_choices(include_blank=self.blank, blank_choice=BLANK_CHOICE_NONE)
else:
return self.get_choices()
def _get_val_from_obj(self, obj):
if obj:
return getattr(obj, self.attname)
else:
return self.get_default()
def flatten_data(self, follow, obj = None):
"""
Returns a dictionary mapping the field's manipulator field names to its
"flattened" string values for the admin view. obj is the instance to
extract the values from.
"""
return {self.attname: self._get_val_from_obj(obj)}
def get_follow(self, override=None):
if override != None:
return override
else:
return self.editable
def bind(self, fieldmapping, original, bound_field_class=BoundField):
return bound_field_class(self, fieldmapping, original)
class AutoField(Field):
empty_strings_allowed = False
@@ -335,8 +383,10 @@ class DateField(Field):
empty_strings_allowed = False
def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
self.auto_now, self.auto_now_add = auto_now, auto_now_add
#HACKs : auto_now_add/auto_now should be done as a default or a pre_save...
if auto_now or auto_now_add:
kwargs['editable'] = False
kwargs['blank'] = True
Field.__init__(self, verbose_name, name, **kwargs)
def get_db_prep_lookup(self, lookup_type, value):
@@ -351,6 +401,13 @@ class DateField(Field):
return datetime.datetime.now()
return value
# Needed because of horrible auto_now[_add] behaviour wrt. editable
def get_follow(self, override=None):
if override != None:
return override
else:
return self.editable or self.auto_now or self.auto_now_add
def get_db_prep_save(self, value):
# Casts dates into string format for entry into database.
if value is not None:
@@ -360,6 +417,10 @@ class DateField(Field):
def get_manipulator_field_objs(self):
return [formfields.DateField]
def flatten_data(self, follow, obj = None):
val = self._get_val_from_obj(obj)
return {self.attname: (val is not None and val.strftime("%Y-%m-%d") or '')}
class DateTimeField(DateField):
def get_db_prep_save(self, value):
# Casts dates into string format for entry into database.
@@ -389,6 +450,12 @@ class DateTimeField(DateField):
return datetime.datetime.combine(d, t)
return self.get_default()
def flatten_data(self,follow, obj = None):
val = self._get_val_from_obj(obj)
date_field, time_field = self.get_manipulator_field_names('')
return {date_field: (val is not None and val.strftime("%Y-%m-%d") or ''),
time_field: (val is not None and val.strftime("%H:%M:%S") or '')}
class EmailField(Field):
def __init__(self, *args, **kwargs):
kwargs['maxlength'] = 75
@@ -587,6 +654,10 @@ class TimeField(Field):
def get_manipulator_field_objs(self):
return [formfields.TimeField]
def flatten_data(self,follow, obj = None):
val = self._get_val_from_obj(obj)
return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')}
class URLField(Field):
def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
if verify_exists:
@@ -647,6 +718,24 @@ class ForeignKey(Field):
else:
return [formfields.IntegerField]
def get_db_prep_save(self,value):
if value == '' or value == None:
return None
else:
return int(value)
def flatten_data(self, follow, obj = None):
if not obj:
# In required many-to-one fields with only one available choice,
# select that one available choice. Note: We have to check that
# the length of choices is *2*, not 1, because SelectFields always
# have an initial "blank" value.
if not self.blank and not self.rel.raw_id_admin and self.choices:
choice_list = self.get_choices_default()
if len(choice_list) == 2:
return { self.attname : choice_list[1][0] }
return Field.flatten_data(self, follow, obj)
class ManyToManyField(Field):
def __init__(self, to, **kwargs):
kwargs['verbose_name'] = kwargs.get('verbose_name', to._meta.verbose_name_plural)
@@ -662,11 +751,14 @@ class ManyToManyField(Field):
def get_manipulator_field_objs(self):
if self.rel.raw_id_admin:
return [formfields.CommaSeparatedIntegerField]
return [formfields.RawIdAdminField]
else:
choices = self.get_choices(include_blank=False)
choices = self.get_choices_default()
return [curry(formfields.SelectMultipleField, size=min(max(len(choices), 5), 15), choices=choices)]
def get_choices_default(self):
return Field.get_choices(self, include_blank=False)
def get_m2m_db_table(self, original_opts):
"Returns the name of the many-to-many 'join' table."
return '%s_%s' % (original_opts.db_table, self.name)
@@ -688,6 +780,25 @@ class ManyToManyField(Field):
'value': len(badkeys) == 1 and badkeys[0] or tuple(badkeys),
}
def flatten_data(self, follow, obj = None):
new_data = {}
if obj:
get_list_func = getattr(obj, 'get_%s_list' % self.rel.singular)
instance_ids = [getattr(instance, self.rel.to.pk.attname) for instance in get_list_func()]
if self.rel.raw_id_admin:
new_data[self.name] = ",".join([str(id) for id in instance_ids])
else:
new_data[self.name] = instance_ids
else:
# In required many-to-many fields with only one available choice,
# select that one available choice.
if not self.blank and not self.rel.edit_inline and not self.rel.raw_id_admin:
choices_list = self.get_choices_default()
if len(choices_list) == 1:
print self.name, choices_list[0][0]
new_data[self.name] = [choices_list[0][0]]
return new_data
class OneToOneField(IntegerField):
def __init__(self, to, to_field=None, **kwargs):
kwargs['verbose_name'] = kwargs.get('verbose_name', 'ID')
@@ -753,6 +864,66 @@ class OneToOne(ManyToOne):
self.lookup_overrides = lookup_overrides or {}
self.raw_id_admin = raw_id_admin
class BoundFieldLine(object):
def __init__(self, field_line, field_mapping, original, bound_field_class=BoundField):
self.bound_fields = [field.bind(field_mapping, original, bound_field_class) for field in field_line]
def __iter__(self):
for bound_field in self.bound_fields:
yield bound_field
def __len__(self):
return len(self.bound_fields)
class FieldLine(object):
def __init__(self, field_locator_func, linespec):
if isinstance(linespec, basestring):
self.fields = [field_locator_func(linespec)]
else:
self.fields = [field_locator_func(field_name) for field_name in linespec]
def bind(self, field_mapping, original, bound_field_line_class=BoundFieldLine):
return bound_field_line_class(self, field_mapping, original)
def __iter__(self):
for field in self.fields:
yield field
def __len__(self):
return len(self.fields)
class BoundFieldSet(object):
def __init__(self, field_set, field_mapping, original, bound_field_line_class=BoundFieldLine):
self.name = field_set.name
self.classes = field_set.classes
self.bound_field_lines = [field_line.bind(field_mapping,original, bound_field_line_class) for field_line in field_set]
def __iter__(self):
for bound_field_line in self.bound_field_lines:
yield bound_field_line
def __len__(self):
return len(self.bound_field_lines)
class FieldSet(object):
def __init__(self, name, classes, field_locator_func, line_specs):
self.name = name
self.field_lines = [FieldLine(field_locator_func, line_spec) for line_spec in line_specs]
self.classes = classes
def __repr__(self):
return "FieldSet:(%s,%s)" % (self.name, self.field_lines)
def bind(self, field_mapping, original, bound_field_set_class=BoundFieldSet):
return bound_field_set_class(self, field_mapping, original)
def __iter__(self):
for field_line in self.field_lines:
yield field_line
def __len__(self):
return len(self.field_lines)
class Admin:
def __init__(self, fields=None, js=None, list_display=None, list_filter=None, date_hierarchy=None,
save_as=False, ordering=None, search_fields=None, save_on_top=False, list_select_related=False):
@@ -766,26 +937,18 @@ class Admin:
self.save_on_top = save_on_top
self.list_select_related = list_select_related
def get_field_objs(self, opts):
"""
Returns self.fields, except with fields as Field objects instead of
field names. If self.fields is None, defaults to putting every
non-AutoField field with editable=True in a single fieldset.
"""
def get_field_sets(self, opts):
if self.fields is None:
field_struct = ((None, {'fields': [f.name for f in opts.fields + opts.many_to_many if f.editable and not isinstance(f, AutoField)]}),)
field_struct = ((None, {
'fields': [f.name for f in opts.fields + opts.many_to_many if f.editable and not isinstance(f, AutoField)]
}),)
else:
field_struct = self.fields
new_fieldset_list = []
for fieldset in field_struct:
new_fieldset = [fieldset[0], {}]
new_fieldset[1].update(fieldset[1])
admin_fields = []
for field_name_or_list in fieldset[1]['fields']:
if isinstance(field_name_or_list, basestring):
admin_fields.append([opts.get_field(field_name_or_list)])
else:
admin_fields.append([opts.get_field(field_name) for field_name in field_name_or_list])
new_fieldset[1]['fields'] = admin_fields
new_fieldset_list.append(new_fieldset)
name = fieldset[0]
fs_options = fieldset[1]
classes = fs_options.get('classes', ())
line_specs = fs_options['fields']
new_fieldset_list.append(FieldSet(name, classes, opts.get_field, line_specs))
return new_fieldset_list