MultiFormDict
For the moment, I am stuck on Django 0.96 on one of our servers at work, but needed the formset functionality from the newer forms module. It is a common problem and easily dealt with by prepending keys with a common token to group forms’ values together. I ended up writing a little derived class that makes things simple.
class MultiFormDict(dict): def __init__(self, separator, *args, **kwargs): """Identical to a regular dict, apart from requiring a `separator` token.""" self.separator = separator self.separator_length = len(separator) super(MultiFormDict, self).__init__(*args, **kwargs) def group_iter(self, key): """Iterator over the values associated with a key.""" key = str(key) for item in self.keys(): if item.startswith(key): item_key = item.replace('%s%s' % (key, self.separator), '') yield item_key, self[item] def group_keys(self): """Iterates over the list of unique group keys in this MultiFormDict.""" seen = set([]) for key in self.keys(): found = key.find(self.separator) if found != -1: k = key[0:found] if k not in seen: seen.add(k) yield k def group_dict(self, key): """Returns a dictionary of keys prepended with key and their values.""" d = {} for k, v in self.group_iter(key): d[k] = v return d
Its usage is pretty basic, but having it factored out in its own class certainly makes it faster to write your own formsets.
post_data = MultiFormDict('-', { '0-title': 'Google', '0-url': '', '1-title': 'Yahoo', '1-url': '', '2-title': 'Python', '2-url': 'http://www.python.org' }) for key in post_data.group_keys(): print 'Form #%s' % key print 'Data: %r' % post_data.group_dict(key) for k, v in post_data.group_iter(key): print '\t', k, '=', v
Again, nothing spectacular, but a useful bit of code for working with large forms.