1
0
mirror of https://github.com/django/django.git synced 2025-06-11 06:29:13 +00:00

magic-removal: command fallbacks working for tabular inline editing in change stage

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@1770 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Robert Wittams 2005-12-23 11:49:54 +00:00
parent 1e36a28d67
commit c017d60d15
6 changed files with 110 additions and 103 deletions

View File

@ -32,12 +32,12 @@
{% if fcw.obj.original %}<a href="/r/{{ fcw.obj.original.content_type_id }}/{{ fcw.obj.original.id }}/">View on site</a>{% endif %} {% if fcw.obj.original %}<a href="/r/{{ fcw.obj.original.content_type_id }}/{{ fcw.obj.original.id }}/">View on site</a>{% endif %}
</td>{% endif %} </td>{% endif %}
<td> <td>
<button class="deletebutton" name="command" value="{{fcw.deletecommand}}">Delete</button> <button class="deletebutton" name="command" value="{{bound_related_object.relation.var_name}}.{{fcw.index}}.delete">Delete</button>
</td> </td>
</tr> </tr>
{% endfor %} </table> {% endfor %} </table>
<button class="addbutton" name="command" value="{{bound_related_object.addcommand}}">Add</button> <button class="addbutton" name="command" value="{{bound_related_object.relation.var_name}}.add">Add</button>
{% for fcw in bound_related_object.form_field_collection_wrappers %} {% for fcw in bound_related_object.form_field_collection_wrappers %}
{% for bound_field in fcw.bound_fields %} {% for bound_field in fcw.bound_fields %}

View File

@ -112,11 +112,12 @@ class FieldWrapper(object):
and self.field.rel.raw_id_admin and self.field.rel.raw_id_admin
class FormFieldCollectionWrapper(object): class FormFieldCollectionWrapper(object):
def __init__(self, field_mapping, fields): def __init__(self, field_mapping, fields, index):
self.field_mapping = field_mapping self.field_mapping = field_mapping
self.fields = fields self.fields = fields
self.bound_fields = [AdminBoundField(field, self.field_mapping, field_mapping['original']) self.bound_fields = [AdminBoundField(field, self.field_mapping, field_mapping['original'])
for field in self.fields] for field in self.fields]
self.index = index
class TabularBoundRelatedObject(BoundRelatedObject): class TabularBoundRelatedObject(BoundRelatedObject):
def __init__(self, related_object, field_mapping, original): def __init__(self, related_object, field_mapping, original):
@ -124,9 +125,9 @@ class TabularBoundRelatedObject(BoundRelatedObject):
self.field_wrapper_list = [FieldWrapper(field) for field in self.relation.editable_fields()] self.field_wrapper_list = [FieldWrapper(field) for field in self.relation.editable_fields()]
fields = self.relation.editable_fields() fields = self.relation.editable_fields()
self.form_field_collection_wrappers = [FormFieldCollectionWrapper(field_mapping, fields) self.form_field_collection_wrappers = [FormFieldCollectionWrapper(field_mapping, fields, i)
for field_mapping in self.field_mappings] for (i,field_mapping) in self.field_mappings.items() ]
self.original_row_needed = max([fw.use_raw_id_admin() for fw in self.field_wrapper_list]) self.original_row_needed = max([fw.use_raw_id_admin() for fw in self.field_wrapper_list])
self.show_url = original and hasattr(self.relation.opts, 'get_absolute_url') self.show_url = original and hasattr(self.relation.opts, 'get_absolute_url')

View File

@ -78,7 +78,6 @@ def change_stage(request, path, object_id):
else: else:
# Populate new_data with a "flattened" version of the current data. # Populate new_data with a "flattened" version of the current data.
new_data = manipulator.flatten_data() new_data = manipulator.flatten_data()
# TODO: do this in flatten_data... # TODO: do this in flatten_data...
# If the object has ordered objects on its admin page, get the existing # If the object has ordered objects on its admin page, get the existing
# order and flatten it into a comma-separated list of IDs. # order and flatten it into a comma-separated list of IDs.

View File

@ -122,10 +122,10 @@ class FormWrapper:
def fill_inline_collections(self): def fill_inline_collections(self):
if not self._inline_collections: if not self._inline_collections:
ic = [] ic = []
related_objects = self.manipulator.get_related_objects() children = self.manipulator.children.items()
for rel_obj in related_objects: for rel_obj, child_manips in children:
data = rel_obj.extract_data(self.data) data = rel_obj.extract_data(self.data)
inline_collection = InlineObjectCollection(self.manipulator, rel_obj, data, self.error_dict) inline_collection = InlineObjectCollection(self.manipulator, rel_obj, child_manips, data, self.error_dict)
ic.append(inline_collection) ic.append(inline_collection)
self._inline_collections = ic self._inline_collections = ic
@ -203,12 +203,13 @@ class FormFieldCollection(FormFieldWrapper):
return ''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')]) return ''.join([field.html_error_list() for field in self.formfield_dict.values() if hasattr(field, 'errors')])
class InlineObjectCollection: class InlineObjectCollection:
"An object that acts like a list of form field collections." "An object that acts like a sparse list of form field collections."
def __init__(self, parent_manipulator, rel_obj, data, errors): def __init__(self, parent_manipulator, rel_obj,child_manips, data, errors):
self.parent_manipulator = parent_manipulator self.parent_manipulator = parent_manipulator
self.rel_obj = rel_obj self.rel_obj = rel_obj
self.data = data self.data = data
self.errors = errors self.errors = errors
self.child_manips = child_manips
self._collections = None self._collections = None
self.name = rel_obj.name self.name = rel_obj.name
@ -230,27 +231,32 @@ class InlineObjectCollection:
def __iter__(self): def __iter__(self):
self.fill() self.fill()
return self._collections.__iter__() return self._collections.values().__iter__()
def items(self):
self.fill()
return self._collections.items()
def fill(self): def fill(self):
if self._collections: if self._collections:
return return
else: else:
var_name = self.rel_obj.opts.object_name.lower() #var_name = self.rel_obj.opts.object_name.lower()
wrapper = [] cols = {}
orig = hasattr(self.parent_manipulator, 'original_object') and self.parent_manipulator.original_object or None #orig = hasattr(self.parent_manipulator, 'original_object') and self.parent_manipulator.original_object or None
orig_list = self.rel_obj.get_list(orig) #orig_list = self.rel_obj.get_list(orig)
for i, instance in enumerate(orig_list):
collection = {'original': instance} for i, manip in enumerate(self.child_manips) :
for f in self.rel_obj.editable_fields(): if manip:
for field_name in f.get_manipulator_field_names(''): collection = {'original': manip.original_object}
full_field_name = '%s.%d.%s' % (var_name, i, field_name) for field in manip.fields:
field = self.parent_manipulator[full_field_name] errors = self.errors.get(field.field_name, [])
data = field.extract_data(self.data) data = field.extract_data(self.data)
errors = self.errors.get(full_field_name, []) last_part = field.field_name[field.field_name.rindex('.') + 1:]
collection[field_name] = FormFieldWrapper(field, data, errors) collection[last_part] = FormFieldWrapper(field, data, errors)
wrapper.append(FormFieldCollection(collection))
self._collections = wrapper cols[i] = FormFieldCollection(collection)
self._collections = cols
class FormField: class FormField:
"""Abstract class representing a form field. """Abstract class representing a form field.

View File

@ -42,20 +42,20 @@ class ManipulatorDescriptor(object):
return self.man return self.man
class ManipulatorHelper(object): class ManipulatorHelper(object):
def __init__(self, manip, related_collection): def __init__(self, manip, related, child_manipulators):
self.manip = manip self.manip = manip
self.related_collection = related_collection self.related = related
self.child_manipulators = child_manipulators
class FillHelper(ManipulatorHelper): class FillHelper(ManipulatorHelper):
def matched_item(self,index, child_manip, obj_data): def matched_item(self,index, child_manip, obj_data):
child_manip._fill_data(obj_data) child_manip._fill_data(obj_data)
def missing_item(self, index, child_manip): def missing_item(self, index, child_manip):
self.related_collection[index] = None self.child_manipulators[index] = None
def new_item(self): def new_item(self, obj_data):
child_manip = self.manip.model.AddManipulator() child_manip = self.manip._add_manipulator_for_child(self.related)
self.related_collection.append(child_manip)
child_manip._fill_data(obj_data) child_manip._fill_data(obj_data)
class SaveHelper(ManipulatorHelper): class SaveHelper(ManipulatorHelper):
@ -65,9 +65,11 @@ class SaveHelper(ManipulatorHelper):
def missing_item(self, index, child_manip): def missing_item(self, index, child_manip):
child_manip.manip.original_object.delete(ignore_objects=[parent.original_object]) child_manip.manip.original_object.delete(ignore_objects=[parent.original_object])
def new_item(self, index, obj_data): def new_item(self, obj_data):
child_manip = self.manip.model.AddManipulator() child_manip = self.manip._add_manipulator_for_child(self.related)
child_manip._save_expanded(obj_data) overrides = { self.related.field :
getattr(self.manip.original_object, self.manip.opts.pk.attname) }
child_manip._save_expanded(obj_data, overrides)
class AutomaticManipulator(Manipulator): class AutomaticManipulator(Manipulator):
def _prepare(cls, model): def _prepare(cls, model):
@ -118,16 +120,20 @@ class AutomaticManipulator(Manipulator):
def get_original_value(self, field): def get_original_value(self, field):
raise NotImplementedError raise NotImplementedError
def get_new_object(self, expanded_data): def get_new_object(self, expanded_data, overrides=None):
params = {} params = {}
overrides = overrides or {}
for f in self.opts.fields: for f in self.opts.fields:
# Fields with auto_now_add should keep their original value in the change stage. over = overrides.get(f, None)
auto_now_add = self.change and getattr(f, 'auto_now_add', False) if over:
if self.follow.get(f.name, None) and not auto_now_add: param = over
param = f.get_manipulator_new_data(expanded_data)
else: else:
param = self.get_original_value(f) # Fields with auto_now_add should keep their original value in the change stage.
auto_now_add = self.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(expanded_data)
else:
param = self.get_original_value(f)
params[f.attname] = param params[f.attname] = param
@ -137,12 +143,12 @@ class AutomaticManipulator(Manipulator):
def _fill_related_objects(self, expanded_data, helper_factory): def _fill_related_objects(self, expanded_data, helper_factory):
for related, manips in self.children.items(): for related, manips in self.children.items():
helper = helper_factory(self, related) helper = helper_factory(self, related, manips)
child_data = expanded_data[related.var_name] child_data = MultiValueDict(expanded_data[related.var_name])
# existing objects # existing objects
for index,manip in enumerate(manips): for index,manip in enumerate(manips):
obj_data = child_data.get(str(index), None) obj_data = child_data.get(str(index), None)
child_data.pop(str(index) ) child_data.pop(str(index), None)
if obj_data != None: if obj_data != None:
#the object has new data #the object has new data
helper.matched_item(index,manip, obj_data ) helper.matched_item(index,manip, obj_data )
@ -151,7 +157,7 @@ class AutomaticManipulator(Manipulator):
helper.missing_item(index,manip) helper.missing_item(index,manip)
if child_data: if child_data:
# There are new objects in the data # There are new objects in the data
for index, obj_data in child_data: for index, obj_data in child_data.items():
helper.new_item(obj_data) helper.new_item(obj_data)
def _fill_data(self, expanded_data): def _fill_data(self, expanded_data):
@ -168,7 +174,7 @@ class AutomaticManipulator(Manipulator):
self._do_command_expanded(expanded_data, command_parts) self._do_command_expanded(expanded_data, command_parts)
def _do_command_expanded(self, expanded_data, command_parts): def _do_command_expanded(self, expanded_data, command_parts):
try: try:
part = command_parts.pop(0) part = command_parts.pop(0)
except IndexError: except IndexError:
raise BadCommand, "Not enough parts in command" raise BadCommand, "Not enough parts in command"
@ -188,40 +194,49 @@ class AutomaticManipulator(Manipulator):
if child_data == None: if child_data == None:
raise BadCommand, "'%s' : could not find data for manipulator collection." % (part,) raise BadCommand, "'%s' : could not find data for manipulator collection." % (part,)
# The next part could be an index of a manipulator, # The next part could be an index of a manipulator,
# or it could be a command on the collection. # or it could be a command on the collection.
try: try:
part = command_parts.pop(0) index_part = command_parts.pop(0)
except IndexError: except IndexError:
raise BadCommand, "Not enough parts in command" raise BadCommand, "Not enough parts in command"
try: try:
index = int(index_part) index = int(index_part)
manip = child_manips.get(index, None) manip = child_manips[index]
if manip == None: if manip == None:
raise BadCommand, "No %s manipulator found for index %s in command." % (part, index) raise BadCommand, "No %s manipulator found for index %s in command." % (part, index)
obj_data = child_data.get(index_part, None) obj_data = child_data.get(index_part, None)
if obj_data == None: if obj_data == None:
raise BadCommand, "Could not find data for manipulator %s in %s collection." % (index, part) raise BadCommand, "Could not find data for manipulator %s in %s collection." % (index, part)
if command_parts == ["delete"]: if command_parts == ["delete"]:
child_manips[index] = None child_manips[index] = None
else: else:
manip._do_command_expanded(obj_data,command_parts) manip._do_command_expanded(obj_data,command_parts)
except ValueError: except ValueError:
# Must be a command on the collection. Possible commands: # Must be a command on the collection. Possible commands:
# add. # add.
if index_part == "add": if index_part == "add":
child_manips.append(related.model.AddManipulator()) self._add_manipulator_for_child(related)
else:
raise BadCommand, "%s, unknown command" % (part)
def _add_manipulator_for_child(self, related):
child_manips = self.children.setdefault(related, [])
fol = self.follow[related.name]
prefix = "%s%s.%s." % (self.name_prefix, related.var_name, len(child_manips) )
child_manip = related.model.AddManipulator(follow=fol,name_prefix=prefix)
child_manips.append(child_manip)
return child_manip
def save(self, new_data): def save(self, new_data):
expanded_data = dot_expand(new_data,MultiValueDict) expanded_data = dot_expand(new_data,MultiValueDict)
return self._save_expanded(expanded_data) return self._save_expanded(expanded_data)
def _save_expanded(self, expanded_data): def _save_expanded(self, expanded_data, overrides = None):
add, change, opts, klass = self.add, self.change, self.opts, self.model add, change, opts, klass = self.add, self.change, self.opts, self.model
new_object = self.get_new_object(expanded_data) new_object = self.get_new_object(expanded_data, overrides)
# First, save the basic object itself. # First, save the basic object itself.
new_object.save() new_object.save()
@ -254,29 +269,6 @@ class AutomaticManipulator(Manipulator):
self._fill_related_objects(expanded_data,SaveHelper) self._fill_related_objects(expanded_data,SaveHelper)
return new_object return new_object
# for related, manips in self.children.items():
# child_data = expanded_data[related.var_name]
# #print "with child:", name
# # Apply changes to existing objects
# for index,manip in enumerate(manips):
# obj_data = child_data.get(str(index), None)
# child_data.pop(str(index) )
# if obj_data != None:
# #save the object with the new data
# #print "saving child data:", obj_data
# manip._save_expanded(obj_data)
# else:
# #delete the object as it was not in the data
# manip.original_object.delete(ignore_objects=[self])
# #print "deleting child object:", manip.original_original
# if child_data:
# # There are new objects in the data, so
# # add them.
# for index, obj_data in child_data:
# manip = related.model.AddManipulator()
# manip._save_expanded(obj_data)
# #print "new data to be added:", child_data
# Save the order, if applicable. # Save the order, if applicable.
#if change and opts.get_ordered_objects(): #if change and opts.get_ordered_objects():
@ -290,9 +282,17 @@ class AutomaticManipulator(Manipulator):
def flatten_data(self): def flatten_data(self):
new_data = {} new_data = {}
for f in self.opts.get_data_holders(self.follow): for f in self.opts.fields + self.opts.many_to_many:
fol = self.follow.get(f.name) fol = self.follow.get(f.name, None)
new_data.update(f.flatten_data(fol, self.original_object)) if fol:
new_data.update(f.flatten_data(fol, self.original_object))
for rel, child_manips in self.children.items():
for manip in child_manips:
if manip:
child_data = manip.flatten_data()
new_data.update(child_data)
new_data = dict([(self.name_prefix +k, v) for k,v in new_data.items()])
return new_data return new_data
class ModelAddManipulator(AutomaticManipulator): class ModelAddManipulator(AutomaticManipulator):

View File

@ -84,7 +84,8 @@ class RelatedObject(object):
if parent_manipulator.original_object: if parent_manipulator.original_object:
meth_name = 'get_%s_list' % self.get_method_name_part() meth_name = 'get_%s_list' % self.get_method_name_part()
list = getattr(parent_manipulator.original_object, meth_name)() list = getattr(parent_manipulator.original_object, meth_name)()
else:
list = []
manipulators = [] manipulators = []
for i,obj in enumerate(list): for i,obj in enumerate(list):
prefix = '%s%s.%d.' % (parent_manipulator.name_prefix, self.var_name, i) prefix = '%s%s.%d.' % (parent_manipulator.name_prefix, self.var_name, i)