Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SmileyChris/853944 to your computer and use it in GitHub Desktop.
Save SmileyChris/853944 to your computer and use it in GitHub Desktop.
from django.utils.datastructures import SortedDict
from django.db.models.fields import AutoField
class EasyFieldsets(object):
"""
A mixin for use with ``ModelAdmin`` and related inline classes allowing
fieldsets to be used without having to manually define all fields
(undefined ones are placed at the end of the ``None`` fieldset).
"""
def __init__(self, *args, **kwargs):
super(EasyFieldsets, self).__init__(*args, **kwargs)
fieldsets = SortedDict(self.fieldsets)
# Get the currently named fields from the fieldsets.
named_fields = []
for fieldset in fieldsets.values():
for field in fieldset['fields']:
if isinstance(field, basestring):
named_fields.append(field)
else:
# Fields can be grouped.
named_fields.extend(field)
# Add any missing fields into the main fieldset.
fields = self.model._meta.fields + self.model._meta.many_to_many
missing_fields = [f.name for f in fields
if f.editable and not isinstance(f, AutoField)
and f.name not in named_fields]
if missing_fields:
if None not in fieldsets:
fieldsets[None] = {}
# Push the missing base fieldset to the top of the fieldset
# order.
fieldsets.keyOrder.remove(None)
fieldsets.keyOrder.insert(0, None)
fields = tuple(missing_fields)
base_fieldset = fieldsets.get(None)
base_fieldset['fields'] = (tuple(base_fieldset.get('fields', []))
+ tuple(missing_fields))
self.fieldsets = fieldsets.items()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment